首页 > 其他 > 详细

vue之MVVM双向绑定原理

时间:2021-06-23 21:51:43      阅读:14      评论:0      收藏:0      [点我收藏+]
class Watcher {
  constructor(obj, key, cb) {
    // Watcher构造函数,先把当前watcher放到一个地方
    window.curWatcher = this
    // 触发getter,在getter里就可以将先前放好的watcher拿出来放到其dep中
    this.value = obj[key]
    // 
    window.curWatcher = null
    this.cb = cb
  }
  update(oldVal, val) {
    this.cb(oldVal, val)
  }
}
class Dep {
  constructor() {
    this.subs = []
  }
  notify(oldVal, val) {
    if (this.subs === []) return
    this.subs.forEach(item => {
      item.update(oldVal, val)
    })
  }
}
//创建Observer递归调用这个函数,
function defineReactive(obj, key, val) {
  let dep = new Dep()
  Object.defineProperty(obj, key, {
    enumerable: true,
    configurable: true,
    get: () => {
      // 收集watcher
      if (window.curWatcher !== undefined) {
        dep.subs.push(window.curWatcher)
      }
      return val
    },
    set: (newVal) => {
      if (val === newVal) return
      // 通知watcher去调用回调函数更新视图
      dep.notify(val, newVal)
      val = newVal
    }
  })
}
function compiler() {
  //模板编译,创建watcher,传递更新视图的回调函数
  //订阅
  new Watcher(data, path, () => {})
}
defineReactive(obj, path, ‘‘)
compiler()

vue之MVVM双向绑定原理

原文:https://www.cnblogs.com/dingtongya/p/14906128.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!