vue数据双向绑定原理--初学习笔记

// 数据存储对象
    let data = {
      price: 20,
      quantity: 5
    }
    console.log("target=null")
    //与data中属性相关的目标函数
    let target = null;


    // 与data属性有关的每个函数保存在一个数组中 
    // 添加相关函数到改数组中
    // 改变时 把该数组的函数都执行一遍
    class Dep {
      constructor() {
        //订阅者
        this.subscribers = [];
      }
      //给订阅者添加依赖
      //target函数是否存在 订阅者是否已经存在
      depend() {
        console.log("depend函数被调用")
        if (target && !this.subscribers.includes(target)) {
          console.log("target函数被添加")
          this.subscribers.push(target)
        }
      }
      //通知订阅者执行保存的函数
      notify() {
        console.log("notify被调用")
        this.subscribers.forEach(sub => sub());
      }
    }
    //便利data每个属性 填加getter和setter构造器
    // 给每个属性添加一个dep实例

    //1. 在get中 给订阅者添加依赖  然后该属性的值
    //2. 在set中,先改变该属性的值 然后给执行订阅者保存的函数
    Object.keys(data).forEach(key=> {
      console.log(key+"被重构属性")
      // 当前属性的值
      let currentVal = data[key];
      const  dep = new Dep();
      Object.defineProperty(data,key,{
        get() {
          dep.depend();
          return currentVal;
        },
        set(newVal) {
          currentVal = newVal;
          dep.notify();
        }
      })
    })

    //执行target函数 的函数
    function watcher(myFunc) {
      target = myFunc;
      console.log("target函数被调用")
      target();
      target = null;
    }

    // 当使用 data.price 和使用 data.quantity时,他们的get函数就被调用
    watcher(()=> {
      data.total = data.price * data.quantity;
    })

在这里插入图片描述

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值