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()

vue之MVVM双向绑定原理

上一篇:LeetCode-018-四数之和


下一篇:关于parameterized测试用例