Vue源码分析——observer

2018-02-23

前言


observer应该是Vue的一个核心模块,也即是Vue的响应式原理。主要通过底层的Object.defineProperty,来定义属性的getter/setter来实现。
每个组件实例都有相应的watcher实例对象,它会在组件渲染的过程中把属性记录为依赖,之后当依赖项的 setter 被调用时,会通知 watcher 重新计算,从而致使它关联的组件得以更新。
data.png

正文


源码的版本是:version: 2.5.13, 当前的源码是用flow.js写的
Observer的整体结构大概是这样的
Observer结构
我们写个简单的App.vue

<template>
  <div id="app">
    <div>
      count: {{count}} 
      <button @click='add'>+</button>
    </div>
  </div>
</template>

<script>
export default {
  name: 'App',
  data () {
    return {
      count: 0
    }
  },
  methods: {
    add () {
      this.count++
    }
  }
}
</script>

data的count会渲染到使视图中,而点击button时,count会添加1,并更新到视图中。这就是响应式,当count修改的时候,就是通知视图去更新;

我们先从Vue怎么初始化data说起

// core/instance/state.js

function initData (vm: Component) {
  let data = vm.$options.data
  data = vm._data = typeof data === 'function'
    ? getData(data, vm)
    : data || {}
  if (!isPlainObject(data)) {
    data = {}
    process.env.NODE_ENV !== 'production' && warn(
      'data functions should return an object:\n' +
      'https://vuejs.org/v2/guide/components.html#data-Must-Be-a-Function',
      vm
    )
  }
  // proxy data on instance
  const keys = Object.keys(data)
  const props = vm.$options.props
  const methods = vm.$options.methods
  let i = keys.length
  while (i--) {
    const key = keys[i]
    if (process.env.NODE_ENV !== 'production') {
      if (methods && hasOwn(methods, key)) {
        warn(
          `Method "${key}" has already been defined as a data property.`,
          vm
        )
      }
    }
    if (props && hasOwn(props, key)) {
      process.env.NODE_ENV !== 'production' && warn(
        `The data property "${key}" is already declared as a prop. ` +
        `Use prop default value instead.`,
        vm
      )
    } else if (!isReserved(key)) {
      // 代理这些函数,  this[key] = this._data[key]
      proxy(vm, `_data`, key)
    }
  }
  // observe data
  // 观察data
  observe(data, true /* asRootData */)
}

初始化data,主要作用是代理了data的这些属性,this[key] = this._data[key],所以我们可以通过this[key]来获取和赋值。
再转移到observe函数的实现

// core/observer/index.js
export function observe (value: any, asRootData: ?boolean): Observer | void {
  if (!isObject(value) || value instanceof VNode) {
    return
  } 
  let ob: Observer | void
  if (hasOwn(value, '__ob__') && value.__ob__ instanceof Observer) {
    ob = value.__ob__
  } else if (
    observerState.shouldConvert &&
    !isServerRendering() &&
    (Array.isArray(value) || isPlainObject(value)) &&
    Object.isExtensible(value) &&
    !value._isVue
  ) {
    ob = new Observer(value)
  }
  if (asRootData && ob) {
    ob.vmCount++
  }
  return ob
}

这段主要new一个Observer实例,已经存在的就不用

// core/observer/index.js
export class Observer {
  value: any;
  dep: Dep;
  vmCount: number; // number of vms that has this object as root $data

  constructor (value: any) {
    this.value = value
    this.dep = new Dep()
    this.vmCount = 0
    def(value, '__ob__', this)
    if (Array.isArray(value)) {
      const augment = hasProto
        ? protoAugment
        : copyAugment
      augment(value, arrayMethods, arrayKeys)
      this.observeArray(value)
    } else {
      this.walk(value)
    }
  }

  /**
   * Walk through each property and convert them into
   * getter/setters. This method should only be called when
   * value type is Object.
   */
  walk (obj: Object) {
    const keys = Object.keys(obj)
    for (let i = 0; i < keys.length; i++) {
      defineReactive(obj, keys[i], obj[keys[i]])
    }
  }

  /**
   * Observe a list of Array items.
   */
  observeArray (items: Array<any>) {
    for (let i = 0, l = items.length; i < l; i++) {
      observe(items[i])
    }
  }
}

该实例有3个属性,valuedepvmCount
value也就是我们赋予它的初始值;
dep是一个Dep实例,我们待会再看它的具体实现。我把它当成一个发布者,等待watcher来订阅; 最后形成依赖关系;
def(value, '__ob__', this),则主要是在value中添加一个__ob__属性,指向this
我们讲讲上面这段代码
constructor方法判断了value是否为数组,是的话就Observe a list of Array items;
最后都会经过walk,重新定义data的属性,转化为响应式属性

我们先看Dep的实现,后面才能更好的讲解defineReactive

export default 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)
  }

  // 订阅,当前watcher添加到subs当中
  depend () { 
    if (Dep.target) {
      Dep.target.addDep(this)
    }
  }

  // 通知到每个subs执行update
  notify () {
    // stabilize the subscriber list first
    const subs = this.subs.slice()
    for (let i = 0, l = subs.length; i < l; i++) {
      subs[i].update()
    }
  }
}

// the current target watcher being evaluated.
// this is globally unique because there could be only one
// watcher being evaluated at any time.
Dep.target = null
const targetStack = []

export function pushTarget (_target: Watcher) {
  if (Dep.target) targetStack.push(Dep.target)
  Dep.target = _target
}

export function popTarget () {
  Dep.target = targetStack.pop()
}

subs就是存储watcher(订阅者)的
Dep.target的值就是当前的watcher
depend()形成依赖关系,把当前的watcher添加进subs中;
notify(),相当于发布,通知所有的订阅者(watcher)执行update

我们再来看defineReactive

// core/observer/index.js
export 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
  }

  // cater for pre-defined getter/setters
  const getter = property && property.get
  const setter = property && property.set

  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
      }
      /* eslint-enable no-self-compare */
      if (process.env.NODE_ENV !== 'production' && customSetter) {
        customSetter()
      }
      if (setter) {
        setter.call(obj, newVal)
      } else {
        val = newVal
      }
      childOb = !shallow && observe(newVal)
      dep.notify()
    }
  })
}

这里形成了闭包,每个属性都有一个dep实例,会一直存在,供getset调用
get方法中,我们已经知道Dep.target就是一个watcher,当Dep.target存在的时候,就会把当前的Dep.target加入到dep实例的subs当中,形成依赖关系
set方法判断是否跟之前的value相同,不相同则执行dep.notify(),通知所有的订阅者(watcher)

目前已大致理解清了结构;
把data的属性遍历,转换为响应式属性,重新定义它的getter/setterdep来存储依赖关系并作为发布者的角色,watcher相当于订阅者
getter获取值的时候,主要用于形成依赖,把当前的watcher加入到需要的属性的dep当中,形成依赖。
setter修改值的时候,通过dep形成的依赖,通知所有订阅了该属性的watcher

最后我们看看watcher的实现

// core/observer/watcher.js
export default class Watcher {
  constructor (
    vm: Component,
    expOrFn: string | Function,
    cb: Function,
    options?: ?Object,
    isRenderWatcher?: boolean
  ) {
    this.vm = vm
    if (isRenderWatcher) {
      vm._watcher = this
    }
    // 把this加入到组件的_watcher当中
    vm._watchers.push(this)
    // options
    if (options) {
      this.deep = !!options.deep
      this.user = !!options.user
      this.lazy = !!options.lazy
      this.sync = !!options.sync
    } else {
      this.deep = this.user = this.lazy = this.sync = false
    }
    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 = function () {}
        process.env.NODE_ENV !== 'production' && warn(
          `Failed watching path: "${expOrFn}" ` +
          'Watcher only accepts simple dot-delimited paths. ' +
          'For full control, use a function instead.',
          vm
        )
      }
    }
    this.value = this.lazy
      ? undefined
      : this.get()
  }
  /**
   * Evaluate the getter, and re-collect dependencies.
   */
  get () {
    // Dep.target赋值为当前实例
    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
  }
  /**
   * Add a dependency to this directive.
   */
  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)
      }
    }
  }
  /**
   * Subscriber interface.
   * Will be called when a dependency changes.
   */
  update () {
    /* istanbul ignore else */
    if (this.lazy) {
      this.dirty = true
    } else if (this.sync) {
      this.run()
    } else {
      queueWatcher(this)
    }
  }

  /**
   * Scheduler job interface.
   * Will be called by the scheduler.
   */
  run () {
    if (this.active) {
      const value = this.get()
      if (
        value !== this.value ||
        // Deep watchers and watchers on Object/Arrays should fire even
        // when the value is the same, because the value may
        // have mutated.
        isObject(value) ||
        this.deep
      ) {
        // set new value
        const oldValue = this.value
        this.value = value
        if (this.user) {
          try {
            this.cb.call(this.vm, value, oldValue)
          } catch (e) {
            handleError(e, this.vm, `callback for watcher "${this.expression}"`)
          }
        } else {
          this.cb.call(this.vm, value, oldValue)
        }
      }
    }
  }
}

lazyfalse的时候,也就是不是懒加载的时候,立即执行get()
pushTarget(this)把Dep.target赋值为当前实例watcher
this.getter就是我们传入的参数expOrFn,它就是来收集依赖的,通过执行里面的函数,获取属性this[key]来执行我们重新定义的响应式属性的getter,形成依赖关系。(不懂的可以回顾defineReactive)。
修改响应式属性的时候,通知订阅了该属性的watcher去触发update(),如果是同步的,立刻执行run(),否则加入到queueWatcher;
run()const value = this.get()会触发this.getter,并且重新更新依赖关系

例如组件在mounted生命周期的时候,里面会创建一个watcher实例,也就是我们所说的每个组件都会创建一个watcher实例。
new Watcher(vm, updateComponent, noop, null, true /* isRenderWatcher */),updateComponent里面需要获取一些需要的响应式属性this._data[key],触发属性的getter,最后形成依赖关系。
修改订阅了的属性的时候,通知该watcherupdate(),最后执行run()run()中执行updateComponent,以达到重新更新视图的效果,并重新获取依赖关系

自己再举个例子:

function getter(){
  return this.a + this.b;
}
const w1 = new Watcher(vm, getter, noop, null);

执行getter的时候,就是为了获取this.athis.b的值,而ab属性已经在defineReactive中重新定义,获取就会属性的触发getter,最后获取形成依赖关系。
当我们要修改a的时候, this.a = 2,就是通知订阅了该属性的w1, 执行w1.update(), 最后run中再执行getter函数,并且重新获取依赖。

理清楚这个例子也就差不多理解这个整个过程了。