vue之MVVM双向绑定原理

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()
posted @ 2021-06-23 18:42  丁同亚的博客  阅读(44)  评论(0编辑  收藏  举报