Vue2.x源码学习笔记(四)——响应式原理之对象的侦测

116 阅读2分钟

observe函数

在初始化的initData函数中,通过observe(data)来使data响应式。observe函数内部会判断目标对象中有没有__ob__属性。如果没有会通过new Observer来添加一个不可枚举的属性__ob__,值就是本身这个Observer类。之后会通过__ob__作为响应式的标记。最后observe函数返回__ob__。

Observer

class Observer {
  value: any;
  dep: Dep;
  vmCount: number; 
  constructor (value: any) {
    this.value = value
    this.dep = new Dep()
    this.vmCount = 0
    def(value, '__ob__', this)
    if (Array.isArray(value)) {
     //数组侦测
    } else {
      this.walk(value)
    }
  }
  walk (obj: Object) {
    const keys = Object.keys(obj)
    for (let i = 0; i < keys.length; i++) {
      defineReactive(obj, keys[i])
    }
  }
}

在new Observer过程中,他不仅会给目标对象添加__ob__这个响应式标记,还会new Dep便于后续收集依赖。对于object类型他会执行walk方法,而walk方法则是循环object中的key。然后执行defineReactive来使其响应式。

defineReactive

function defineReactive (
  obj: Object,
  key: string,
  val: any,
  customSetter?: ?Function,
  shallow?: boolean
) {
  const dep = new Dep()

  const property = Object.getOwnPropertyDescriptor(obj, key)
  if (property && property.configurable === false) {
    return
  }
  const getter = property && property.get
  const setter = property && property.set
  if ((!getter || setter) && arguments.length === 2) {
    val = obj[key]
  }

  let childOb = !shallow && observe(val)
  Object.defineProperty(obj, key, {
    enumerable: true,
    configurable: true,
    get: function reactiveGetter () {
      const value = getter ? getter.call(obj) : val
      if (Dep.target) {
        dep.depend()
        if (childOb) {
          childOb.dep.depend()
          if (Array.isArray(value)) {
            dependArray(value)
          }
        }
      }
      return value
    },
    set: function reactiveSetter (newVal) {
      const value = getter ? getter.call(obj) : val
      /* eslint-disable no-self-compare */
      if (newVal === value || (newVal !== newVal && value !== value)) {
        return
      }
      if (getter && !setter) return
      if (setter) {
        setter.call(obj, newVal)
      } else {
        val = newVal
      }
      childOb = !shallow && observe(newVal)
      dep.notify()
    }
  })
}

首先我们通过new Dep创建一个dep,用于给这个属性收集依赖,然后再递归执行observe(val)。当读取属性时会调用get方法,get中通过dep.depend()来收集依赖。如果这个值有__ob__,则__ob__对应的Observer类也会收集依赖。在修改值时会调用set,set中会通过observe(newVal)来对新赋的值进行响应式化,并通过dep.notify通知依赖更新。

Object.defineProperty

对象的侦测是靠Object.defineProperty(obj,prop, descriptor)来实现的。第一个参数是操作的对象,第二个参数是对象的key,第三个参数是配置。descriptor有以下配置:

  • configurable:true时可以修改属性,可以delete属性。默认为false。
  • enumerable:true时表示key可枚举。默认为false。
  • writable:true时属性的value才能被赋值运算改变,默认为false。
  • get:属性读取时触发。Vue就是在这里收集依赖。
  • set:属性设置值时触发。Vue在这里触发更新。
  • value:属性值。

Dep

class Dep {
  static target: ?Watcher;
  id: number;
  subs: Array<Watcher>;
  constructor () {
    this.id = uid++
    this.subs = []
  }
  addSub (sub: Watcher) {
    this.subs.push(sub)
  }
  removeSub (sub: Watcher) {
    remove(this.subs, sub)
  }
  depend () {
    if (Dep.target) {
      Dep.target.addDep(this)
    }
  }
  notify () {
    const subs = this.subs.slice()
    if (process.env.NODE_ENV !== 'production' && !config.async) {
      subs.sort((a, b) => a.id - b.id)
    }
    for (let i = 0, l = subs.length; i < l; i++) {
      subs[i].update()
    }
  }
}

在new Dep时会给每一个dep绑定一个自增id,并且创建一个subs空数组,用于收集watcher依赖。

上面我们说到当读取数据时,会调用dep的depend方法去收集依赖。该方法中会通过Dep.target获得当前的watcher。然后调用当前watcher的addDep方法,addDep其实就是将dep和watcher绑定:给wathcer的deps数组中添加当前dep,并在dep的subs数组中添加当前watcher。

当数据更新时通过notify去派发更新。它遍历排序好的subs数组,也就是调用每一个watcher的update方法去更新时图。

Watcher

class Watcher {
  constructor (
    vm: Component,
    expOrFn: string | Function,
    cb: Function,
    options?: ?Object,
    isRenderWatcher?: boolean
  ) {
    this.vm = vm
    if (isRenderWatcher) {
      vm._watcher = this
    }
    vm._watchers.push(this)
    this.cb = cb
    this.id = ++uid 
    this.active = true
    this.dirty = this.lazy 
    this.deps = []
    this.newDeps = []
    this.depIds = new Set()
    this.newDepIds = new Set()
    this.expression = process.env.NODE_ENV !== 'production'
      ? expOrFn.toString()
      : ''
    // parse expression for getter
    if (typeof expOrFn === 'function') {
      this.getter = expOrFn
    } else {
      this.getter = parsePath(expOrFn)
      if (!this.getter) {
        this.getter = noop
      }
    }
    this.value = this.lazy
      ? undefined
      : this.get()
  }
  get () {
   //核心
  }
  addDep (dep: Dep) {
    const id = dep.id
    if (!this.newDepIds.has(id)) {
      this.newDepIds.add(id)
      this.newDeps.push(dep)
      if (!this.depIds.has(id)) {
        dep.addSub(this)
      }
    }
  }
  update () {
    if (this.lazy) {
      this.dirty = true
    } else if (this.sync) {
      this.run()
    } else {
      queueWatcher(this)
    }
  }
  run () {
    if (this.active) {
      const value = this.get()
      if (
        value !== this.value ||
        isObject(value) ||
        this.deep
      ) {
        const oldValue = this.value
        this.value = value
        this.cb.call(this.vm, value, oldValue)
        }
      }
    }
  }
}

update方法中如果sync属性为true则立即执行run方法。否则会通过queueWatcher异步更新队列去执行run方法。

run方法会调用get方法去获得watcher的新值,当新值和旧值不同时会去调用cb回调函数。

get

get () {
    pushTarget(this)
    let value
    const vm = this.vm
    try {
      value = this.getter.call(vm, vm)
    } catch (e) {
      if (this.user) {
        handleError(e, vm, `getter for watcher "${this.expression}"`)
      } else {
        throw e
      }
    } finally {
      // "touch" every property so they are all tracked as
      // dependencies for deep watching
      if (this.deep) {
        traverse(value)
      }
      popTarget()
      this.cleanupDeps()
    }
    return value
  }

get方法中会先将当前操作的watcher,存放在Dep.target,然后调用传入的参数的getter方法,调用getter其实就是会去更新试图,并且会触发收集依赖的过程。最后再将Dep.target置为null,更新完后,清除旧的依赖。