vue源碼解讀(一)Observer/Dep/Watcher是如何實現數據綁定的


歡迎star我的github倉庫,共同學習~目前vue源碼學習系列已經更新了5篇啦~

https://github.com/yisha0307/...

快速跳轉:

  • Vue的雙向綁定原理(已完成)
  • 說說vue中的Virtual DOM(已完成)
  • React diff和Vue diff實現差別
  • Vue中的異步更新策略(已完成)
  • Vuex的實現理解
  • Typescript學習筆記(持續更新ing)
  • Vue源碼中閉包的使用(已完成)

介紹

最近在學習vue和vuex的源碼,記錄自己的一些學習心得。主要借鑒了染陌同學的《Vue.js 源碼解析 》 和DMQ的mvvm。前者對vue和vuex的源碼做了注解和詳細的中文doc,后者剖析了vue的實現原理,手動實現了mvvm。

我的記錄主要是自己的一些對vue源碼的理解,如果想要看更系統的介紹,還是推薦上面列的兩位大神的工程~

文章中引用的代碼的英文注釋是尤大的,中文注釋一些是染陌的,一些是我的補充理解。可能有理解不對的地方,歡迎評論指出或者給我的github提issue。感謝~

數據綁定原理

正如尤大在vue的教程深入響應式原理里寫的那樣,Vue內部主要靠劫持Object.defineProperty()的getter和setter方法,在每次get數據的時候注入依賴,在set數據的時候發布消息給訂閱者,從而實現DOM的更新。因為Object.defineProperty()沒有辦法在IE8或者更低版本的瀏覽器中實現,所以Vue是不能支持這些瀏覽器的。

看一下官網提供的圖片:

在組件渲染操作的時候("Touch"), 觸發Data中的getter(會保證只有用到的data才會觸發依賴,看了源碼之后,其實是每一個Data的key對應的value都會有一個Dep, 收集一組subs<Array: Watcher>),在更新數據的時候,觸發setter, 通過Dep.notify()通知所有的subs進行更新,watcher又通過回調函數通知組件進行更新,通過virtual DOM和diff計算實現optimize, 完成re-render。

在整個源碼當中,比較重要的幾個概念就是Observer/Dep/Watcher。下面主要分析一下這三類的處理。

Observer

Observer的作用是對整個Data進行監聽,在initData這個初始方法里使用observe(data),Observer類內部通過defineReactive方法劫持data的每一個屬性的getter和setter。看一下源碼:

export function observe (value: any, asRootData: ?boolean): Observer | void {
  /*判斷Data是否是一個對象*/
  if (!isObject(value)) {
    return
  }
  let ob: Observer | void

  /*這里用__ob__這個屬性來判斷是否已經有Observer實例,如果沒有Observer實例則會新建一個Observer實例並賦值給__ob__這個屬性,如果已有Observer實例則直接返回該Observer實例*/
  if (hasOwn(value, '__ob__') && value.__ob__ instanceof Observer) {
    ob = value.__ob__
  } else if (
    /*這里的判斷是為了確保value是單純的對象,而不是函數或者是Regexp等情況。*/
    observerState.shouldConvert &&
    !isServerRendering() &&
    (Array.isArray(value) || isPlainObject(value)) &&
    Object.isExtensible(value) &&
    !value._isVue
  ) {
    // 創建一個Observer實例,綁定data進行監聽
    ob = new Observer(value)
  }
  if (asRootData && ob) {

    /*如果是根數據則計數,后面Observer中的observe的asRootData非true*/
    ob.vmCount++
  }
  return ob
}

Vue的響應式數據都會有一個__ob__作為標記,里面存放了Observer實例,防止重復綁定。

再看一下Observer類的源碼:

/**
 * Observer class that are attached to each observed
 * object. Once attached, the observer converts target
 * object's property keys into getter/setters that
 * collect dependencies and dispatches updates.
 */
export class  {
  value: any;
  dep: Dep; // 每一個Data的屬性都會綁定一個dep,用於存放watcher arr
  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

    /*
        /vue-src/core/util/lang.js:
        function def (obj: Object, key: string, val: any, enumerable?: boolean) {
            Object.defineProperty(obj, key, {
                value: val,
                enumerable: !!enumerable,
                writable: true,
                configurable: true
            })
        }
    */
    def(value, '__ob__', this) // 這個def的意思就是把Observer實例綁定到Data的__ob__屬性上去
    if (Array.isArray(value)) {

      /*
          如果是數組,將修改后可以截獲響應的數組方法替換掉該數組的原型中的原生方法,達到監聽數組數據變化響應的效果。
      */
      const augment = hasProto
        ? protoAugment  /*直接覆蓋原型的方法來修改目標對象*/
        : copyAugment   /*定義(覆蓋)目標對象或數組的某一個方法*/
      augment(value, arrayMethods, arrayKeys)
      /*Github:https://github.com/answershuto*/
      /*如果是數組則需要遍歷數組的每一個成員進行observe*/
      this.observeArray(value)
    } else {
      /*如果是對象則直接walk進行綁定*/
      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)

    /*
    walk方法會遍歷對象的每一個屬性進行defineReactive綁定
    defineReactive: 劫持data的getter和setter
    */
    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>) {
    /*
    數組需要遍歷每一個成員進行observe
    */
    for (let i = 0, l = items.length; i < l; i++) {
      observe(items[i])
    }
  }
}

可以看到,Observer類主要干了以下幾件事:

  • 給data綁定一個__ob__屬性,用來存放Observer實例,避免重復綁定
  • 如果data是Object, 遍歷對象的每一個屬性進行defineReactive綁定
  • 如果data是Array, 則需要對每一個成員進行observe。vue.js會重寫Array的push、pop、shift、unshift、splice、sort、reverse這7個方法,保證之后pop/push等操作進去的對象也有進行雙向綁定. (具體代碼參見observer/array.js)

defineReactive()

如上述源碼所示,Observer類主要是靠遍歷data的每一個屬性,使用defineReactive()方法劫持getter和setter方法, 下面來具體看一下defineReactive:

export function defineReactive (
  obj: Object,
  key: string,
  val: any,
  customSetter?: Function
) {
  /*在閉包中定義一個dep對象*/
  const dep = new Dep()

  const property = Object.getOwnPropertyDescriptor(obj, key)
  if (property && property.configurable === false) {
    return
  }

  /*如果之前該對象已經預設了getter以及setter函數則將其取出來,新定義的getter/setter中會將其執行,保證不會覆蓋之前已經定義的getter/setter。*/
  // cater for pre-defined getter/setters
  const getter = property && property.get
  const setter = property && property.set

  /*對象的子對象也會進行observe*/
  let childOb = observe(val)
  Object.defineProperty(obj, key, {
    enumerable: true,
    configurable: true,
    get: function reactiveGetter () {
      /*如果原本對象擁有getter方法則執行*/
      const value = getter ? getter.call(obj) : val
    //   Dep.target:全局屬性,用於指向某一個watcher,用完即丟
      if (Dep.target) {
        /*
        進行依賴收集
        dep.depend()內部實現addDep,往dep中添加watcher實例 (具體參考Dep.prototype.depend的代碼)
        depend的時候會根據id判斷watcher有沒有添加過,避免重復添加依賴
        */
        dep.depend()
        if (childOb) {
          /*子對象進行依賴收集,其實就是將同一個watcher觀察者實例放進了兩個depend中,一個是正在本身閉包中的depend,另一個是子元素的depend*/
          childOb.dep.depend()
        }
        if (Array.isArray(value)) {
          /*是數組則需要對每一個成員都進行依賴收集,如果數組的成員還是數組,則遞歸。*/
          dependArray(value)
        }
      }
      return value
    },
    set: function reactiveSetter (newVal) {
      /*通過getter方法獲取當前值,與新值進行比較,一致則不需要執行下面的操作*/
      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方法則執行setter*/
        setter.call(obj, newVal)
      } else {
        val = newVal
      }
      /*新的值需要重新進行observe,保證數據響應式*/
      childOb = observe(newVal)
      /*dep對象通知所有的觀察者*/
      dep.notify()
    }
  })
}

defineReactive()方法主要通過Object.defineProperty()做了以下幾件事:

  • 在閉包里定義一個Dep實例;
  • getter用來收集依賴,Dep.target是一個全局的屬性,指向的那個watcher收集到dep里來(如果之前添加過就不會重復添加);
  • setter是在更新value的時候通知所有getter時候通知所有收集的依賴進行更新(dep.notify)。這邊會做一個判斷,如果newVal和oldVal一樣,就不會有操作。

Dep

在上面的defineReactive中提到了Dep,於是接下來看一下Dep的源碼, dep主要是用來在數據更新的時候通知watchers進行更新:

/**
 * A dep is an observable that can have multiple
 * directives subscribing to it.
 */
export default class Dep {
  static target: ?Watcher;
  id: number;
  subs: Array<Watcher>;

  constructor () {
    this.id = uid++
    // subs: Array<Watcher>
    this.subs = []
  }

  /*添加一個觀察者對象*/
  addSub (sub: Watcher) {
    this.subs.push(sub)
  }

  /*移除一個觀察者對象*/
  removeSub (sub: Watcher) {
    remove(this.subs, sub)
  }

  /*依賴收集,當存在Dep.target的時候添加觀察者對象*/
//   在defineReactive的getter中會用到dep.depend()
  depend () {
    if (Dep.target) {
        // Dep.target指向的是一個watcher
      Dep.target.addDep(this)
    }
  }

  /*通知所有訂閱者*/
  notify () {
    // stabilize the subscriber list first
    const subs = this.subs.slice()
    for (let i = 0, l = subs.length; i < l; i++) {
        // 調用每一個watcher的update
      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
/*依賴收集完需要將Dep.target設為null,防止后面重復添加依賴。*/
  • Dep是一個發布者,可以訂閱多個觀察者,依賴收集之后Dep中會有一個subs存放一個或多個觀察者,在數據變更的時候通知所有的watcher。
  • 再復習一下,Dep和Observer的關系就是Observer監聽整個data,遍歷data的每個屬性給每個屬性綁定defineReactive方法劫持getter和setter, 在getter的時候往Dep類里塞依賴(dep.depend),在setter的時候通知所有watcher進行update(dep.notify)

Watcher

watcher接受到通知之后,會通過回調函數進行更新。

接下來我們要仔細看一下watcher的源碼。由之前的Dep代碼可知的是,watcher需要實現以下兩個作用:

  • dep.depend()的時候往dep里添加自己;
  • dep.notify()的時候調用watcher.update()方法,對視圖進行更新;

同時要注意的是,watcher有三種:render watcher/ computed watcher/ user watcher(就是vue方法中的那個watch)

export default class Watcher {
  vm: Component;
  expression: string; // 每一個DOM attr對應的string
  cb: Function; // update的時候的回調函數
  id: number;
  deep: boolean;
  user: boolean;
  lazy: boolean;
  sync: boolean;
  dirty: boolean;
  active: boolean;
  deps: Array<Dep>;
  newDeps: Array<Dep>;
  depIds: ISet;
  newDepIds: ISet;
  getter: Function;
  value: any;

  constructor (
    vm: Component,
    expOrFn: string | Function,
    cb: Function,
    options?: Object
  ) {
    this.vm = vm
    /*_watchers存放訂閱者實例*/
    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.cb = cb
    this.id = ++uid // uid for batching
    this.active = true
    this.dirty = this.lazy // for lazy watchers
    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
    /*把表達式expOrFn解析成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.
   */
   /*獲得getter的值並且重新進行依賴收集*/
  get () {
    /*將自身watcher觀察者實例設置給Dep.target,用以依賴收集。*/
    pushTarget(this)
    let value
    const vm = this.vm

    /*
      執行了getter操作,看似執行了渲染操作,其實是執行了依賴收集。
      在將Dep.target設置為自身觀察者實例以后,執行getter操作。
      譬如說現在的的data中可能有a、b、c三個數據,getter渲染需要依賴a跟c,
      那么在執行getter的時候就會觸發a跟c兩個數據的getter函數,
      在getter函數中即可判斷Dep.target是否存在然后完成依賴收集,
      將該觀察者對象放入閉包中的Dep的subs中去。
    */
    if (this.user) {
        // this.user: 判斷是不是vue中那個watch方法綁定的watcher
      try {
        value = this.getter.call(vm, vm)
      } catch (e) {
        handleError(e, vm, `getter for watcher "${this.expression}"`)
      }
    } else {
      value = this.getter.call(vm, vm)
    }
    // "touch" every property so they are all tracked as
    // dependencies for deep watching
    /*如果存在deep,則觸發每個深層對象的依賴,追蹤其變化*/
    if (this.deep) {
      /*遞歸每一個對象或者數組,觸發它們的getter,使得對象或數組的每一個成員都被依賴收集,形成一個“深(deep)”依賴關系*/
      traverse(value)
    }

    /*將觀察者實例從target棧中取出並設置給Dep.target*/
    popTarget()
    this.cleanupDeps()
    return value
  }

  /**
   * Add a dependency to this directive.
   */
   /*添加一個依賴關系到Deps集合中*/
 //  在dep.depend()中調用的是Dep.target.addDep()
  addDep (dep: Dep) {
    const id = dep.id
    if (!this.newDepIds.has(id)) {
        // newDepIds和newDeps記錄watcher實例所用到的dep,比如某個computed watcher其實用到了data里的a/b/c三個屬性,那就需要記錄3個dep
      this.newDepIds.add(id)
      this.newDeps.push(dep)
      if (!this.depIds.has(id)) {
        //  作用是往dep的subs里添加自己(Watcher實例)
        //  但是會先判斷一下id,如果subs里有相同的id就不會重復添加
        dep.addSub(this)
      }
    }
  }

  /**
   * Clean up for dependency collection.
   */
   /*清理依賴收集*/
  cleanupDeps () {
    /*移除所有觀察者對象*/
    let i = this.deps.length
    while (i--) {
      const dep = this.deps[i]
      if (!this.newDepIds.has(dep.id)) {
        dep.removeSub(this)
      }
    }
    let tmp = this.depIds
    this.depIds = this.newDepIds
    this.newDepIds = tmp
    this.newDepIds.clear()
    tmp = this.deps
    this.deps = this.newDeps
    this.newDeps = tmp
    this.newDeps.length = 0
  }

  /**
   * Subscriber interface.
   * Will be called when a dependency changes.
   */
//   dep.notify的時候會逐個調用watcher的update方法
  update () {
    /* istanbul ignore else */
    if (this.lazy) {
      this.dirty = true
    } else if (this.sync) {
      /*同步則執行run直接渲染視圖*/
      // 基本不會用到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.
        /*
            即便值相同,擁有Deep屬性的觀察者以及在對象/數組上的觀察者應該被觸發更新,因為它們的值可能發生改變。
        */
        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)
        }
      }
    }
  }

  /**
   * Evaluate the value of the watcher.
   * This only gets called for lazy watchers.
   */
   /*獲取觀察者的值*/
  evaluate () {
    this.value = this.get()
    this.dirty = false
  }

  /**
   * Depend on all deps collected by this watcher.
   */
   /*收集該watcher的所有deps依賴*/
  depend () {
    let i = this.deps.length
    while (i--) {
      this.deps[i].depend()
    }
  }

  /**
   * Remove self from all dependencies' subscriber list.
   */
   /*將自身從所有依賴收集訂閱列表刪除*/
  teardown () {
    if (this.active) {
      // remove self from vm's watcher list
      // this is a somewhat expensive operation so we skip it
      // if the vm is being destroyed.
      /*從vm實例的觀察者列表中將自身移除,由於該操作比較耗費資源,所以如果vm實例正在被銷毀則跳過該步驟。*/
      if (!this.vm._isBeingDestroyed) {
        remove(this.vm._watchers, this)
      }
      let i = this.deps.length
      while (i--) {
        this.deps[i].removeSub(this)
      }
      this.active = false
    }
  }
}

要注意的是,watcher中有個sync屬性,絕大多數情況下,watcher並不是同步更新的,而是采用異步更新的方式,也就是調用queueWatcher(this)推送到觀察者隊列當中,待nextTick的時候進行調用。


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM