Vue源碼探究-數據綁定的實現

Vue源碼探究-數據綁定的實現

本篇代碼位於vue/src/core/observer/

在總結完數據綁定實現的邏輯架構一篇後,已經對Vue的數據觀察系統的角色和各自的功能有了比較透徹的瞭解,這一篇繼續仔細分析下源碼的具體實現。

Observer

// Observer類用來附加到每個觀察對象上。
// 將被觀察目標對象的屬性鍵名轉換成存取器,
// 以此收集依賴和派發更新
/**
 * Observer class that is attached to each observed
 * object. Once attached, the observer converts the target
 * object's property keys into getter/setters that
 * collect dependencies and dispatch updates.
 */
 // 定義並導出 Observer 類
export class Observer {
  // 初始化觀測對象,依賴對象,實例計數器三個實例屬性
  value: any;
  dep: Dep;
  vmCount: number; // number of vms that has this object as root $data

  // 構造函數接受被觀測對象參數
  constructor (value: any) {
    // 將傳入的觀測對象賦予實例的value屬性
    this.value = value
    // 創建新的Dep依賴對象實例賦予dep屬性
    this.dep = new Dep()
    // 初始化實例的vmCount爲0
    this.vmCount = 0
    // 將實例掛載到觀測對象的'__ob__‘屬性上
    def(value, '__ob__', this)
    // 如果觀測對象是數組
    if (Array.isArray(value)) {
      // 判斷是否可以使用__proto__屬性,以此甚至augment含糊
      const augment = hasProto
        ? protoAugment
        : copyAugment
      // 攔截原型對象並重新添加數組原型方法
      // 這裏應該是爲了修復包裝存取器破壞了數組對象的原型繼承方法的問題
      augment(value, arrayMethods, arrayKeys)
      // 觀察數組中的對象
      this.observeArray(value)
    } else {
      // 遍歷每一個對象屬性轉換成包裝後的存取器
      this.walk(value)
    }
  }

  // walk方法用來遍歷對象的每一個屬性,並轉化成存取器
  // 只在觀測值是對象的情況下調用
  /**
   * 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])
    }
  }

  // 觀察數組對象
  /**
   * Observe a list of Array items.
   */
  observeArray (items: Array<any>) {
    // 遍歷每一個數組對象,並繼續觀察
    for (let i = 0, l = items.length; i < l; i++) {
      observe(items[i])
    }
  }
}

// 下面是兩個輔助函數,用來根據是否可以使用對象的 __proto__屬性來攔截原型
// 函數比較簡單,不詳細解釋了
// helpers

/**
 * Augment an target Object or Array by intercepting
 * the prototype chain using __proto__
 */
function protoAugment (target, src: Object, keys: any) {
  /* eslint-disable no-proto */
  target.__proto__ = src
  /* eslint-enable no-proto */
}

/**
 * Augment an target Object or Array by defining
 * hidden properties.
 */
/* istanbul ignore next */
function copyAugment (target: Object, src: Object, keys: Array<string>) {
  for (let i = 0, l = keys.length; i < l; i++) {
    const key = keys[i]
    def(target, key, src[key])
  }
}

// observe函數用來爲觀測值創建觀察目標實例
// 如果成功被觀察則返回觀察目標,或返回已存在觀察目標
/**
 * Attempt to create an observer instance for a value,
 * returns the new observer if successfully observed,
 * or the existing observer if the value already has one.
 */
 // 定義並導出observe函數,接受觀測值和是否作爲data的根屬性兩個參數
 // 返回Observer類型對象或空值
export function observe (value: any, asRootData: ?boolean): Observer | void {
  // 判斷是否爲所要求的對象,否則不繼續執行
  if (!isObject(value) || value instanceof VNode) {
    return
  }
  // 定義Observer類型或空值的ob變量
  let ob: Observer | void
  // 如果觀測值具有__ob__屬性,並且其值是Observer實例,將其賦予ob
  if (hasOwn(value, '__ob__') && value.__ob__ instanceof Observer) {
    ob = value.__ob__
  } else if (
    // 如果shouldObserve爲真,且不是服務器渲染,觀測值是數組或者對象
    // 觀測值可擴展,且觀測值不是Vue實例,則創建新的觀察目標實例賦予ob
    // 這裏發現了在Vue核心類創建實例的時候設置的_isVue的用途了
    shouldObserve &&
    !isServerRendering() &&
    (Array.isArray(value) || isPlainObject(value)) &&
    Object.isExtensible(value) &&
    !value._isVue
  ) {
    ob = new Observer(value)
  }
  // 如果asRootData爲真且ob對象存在,ob.vmCount自增
  if (asRootData && ob) {
    ob.vmCount++
  }
  // 返回ob
  return ob
}

// defineReactive函數用來爲觀測值包賺存取器
/**
 * Define a reactive property on an Object.
 */
// 定義並導出defineReactive函數,接受參數觀測源obj,屬性key, 值val,
// 自定義setter方法customSetter,是否進行遞歸轉換shallow五個參數
export function defineReactive (
  obj: Object,
  key: string,
  val: any,
  customSetter?: ?Function,
  shallow?: boolean
) {
  // 創建依賴對象實例
  const dep = new Dep()

  // 獲取obj的屬性描述符
  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
  // 如果不存在getter或存在settter,且函數只傳入2個參數,手動設置val值
  // 這裏主要是Obserber的walk方法裏使用的情況,只傳入兩個參數
  if ((!getter || setter) && arguments.length === 2) {
    val = obj[key]
  }
  // 判斷是否遞歸觀察子對象,並將子對象屬性都轉換成存取器,返回子觀察目標
  let childOb = !shallow && observe(val)
  // 重新定義屬性
  Object.defineProperty(obj, key, {
    enumerable: true,
    configurable: true,
    // 設置getter
    get: function reactiveGetter () {
      // 如果預定義的getter存在則value等於getter調用的返回值
      // 否則直接賦予屬性值
      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
    },
    // 設置setter,接收新值newVal參數
    set: function reactiveSetter (newVal) {
      // 如果預定義的getter存在則value等於getter調用的返回值
      // 否則直接賦予屬性值
      const value = getter ? getter.call(obj) : val
      // 如果新值等於舊值或者新值舊值爲null則不執行
      /* eslint-disable no-self-compare */
      if (newVal === value || (newVal !== newVal && value !== value)) {
        return
      }
      // 非生產環境下如果customSetter存在,則調用customSetter
      /* eslint-enable no-self-compare */
      if (process.env.NODE_ENV !== 'production' && customSetter) {
        customSetter()
      }
      // 如果預定義setter存在則調用,否則直接更新新值
      if (setter) {
        setter.call(obj, newVal)
      } else {
        val = newVal
      }
      // 判斷是否遞歸觀察子對象並返回子觀察目標
      childOb = !shallow && observe(newVal)
      // 發佈變更通知
      dep.notify()
    }
  })
}


// 下面是單獨定義並導出的動態增減屬性時觀測的函數
// set函數用來對程序執行中動態添加的屬性進行觀察並轉換存取器,不詳細解釋
/**
 * Set a property on an object. Adds the new property and
 * triggers change notification if the property doesn't
 * already exist.
 */
export function set (target: Array<any> | Object, key: any, val: any): any {
  if (process.env.NODE_ENV !== 'production' &&
    (isUndef(target) || isPrimitive(target))
  ) {
    warn(`Cannot set reactive property on undefined, null, or primitive value: ${(target: any)}`)
  }
  if (Array.isArray(target) && isValidArrayIndex(key)) {
    target.length = Math.max(target.length, key)
    target.splice(key, 1, val)
    return val
  }
  if (key in target && !(key in Object.prototype)) {
    target[key] = val
    return val
  }
  const ob = (target: any).__ob__
  if (target._isVue || (ob && ob.vmCount)) {
    process.env.NODE_ENV !== 'production' && warn(
      'Avoid adding reactive properties to a Vue instance or its root $data ' +
      'at runtime - declare it upfront in the data option.'
    )
    return val
  }
  if (!ob) {
    target[key] = val
    return val
  }
  defineReactive(ob.value, key, val)
  ob.dep.notify()
  return val
}

// Delete函數用來對程序執行中動態刪除的屬性發布變更通知,不詳細解釋
/**
 * Delete a property and trigger change if necessary.
 */
export function del (target: Array<any> | Object, key: any) {
  if (process.env.NODE_ENV !== 'production' &&
    (isUndef(target) || isPrimitive(target))
  ) {
    warn(`Cannot delete reactive property on undefined, null, or primitive value: ${(target: any)}`)
  }
  if (Array.isArray(target) && isValidArrayIndex(key)) {
    target.splice(key, 1)
    return
  }
  const ob = (target: any).__ob__
  if (target._isVue || (ob && ob.vmCount)) {
    process.env.NODE_ENV !== 'production' && warn(
      'Avoid deleting properties on a Vue instance or its root $data ' +
      '- just set it to null.'
    )
    return
  }
  if (!hasOwn(target, key)) {
    return
  }
  delete target[key]
  if (!ob) {
    return
  }
  ob.dep.notify()
}

// 特殊處理數組的依賴收集的函數,遞歸的對數組中的成員執行依賴收集
/**
 * Collect dependencies on array elements when the array is touched, since
 * we cannot intercept array element access like property getters.
 */
function dependArray (value: Array<any>) {
  for (let e, i = 0, l = value.length; i < l; i++) {
    e = value[i]
    e && e.__ob__ && e.__ob__.dep.depend()
    if (Array.isArray(e)) {
      dependArray(e)
    }
  }
}

Dep

let uid = 0

// dep是個可觀察對象,可以有多個指令訂閱它
/**
 * A dep is an observable that can have multiple
 * directives subscribing to it.
 */
// 定義並導出Dep類
export default class Dep {
  // 定義變量
  // 私有變量,當前評估watcher對象
  static target: ?Watcher;
  // dep實例Id
  id: number;
  // dep實例監視器/訂閱者數組
  subs: Array<Watcher>;

  // 定義構造器
  constructor () {
    // 初始化時賦予遞增的id
    this.id = uid++
    this.subs = []
  }

  // 定義addSub方法,接受Watcher類型的sub參數
  addSub (sub: Watcher) {
    // 向subs數組裏添加新的watcher
    this.subs.push(sub)
  }

  // 定義removeSub方法,接受Watcher類型的sub參數
  removeSub (sub: Watcher) {
    // 從subs數組裏移除指定watcher
    remove(this.subs, sub)
  }

  // 定義depend方法,將觀察對象和watcher建立依賴
  depend () {
    // 在創建Wacther的時候會將在創建的Watcher賦值給Dep.target
    // 建立依賴時如果存在Watcher,則會調用Watcher的addDep方法
    if (Dep.target) {
      Dep.target.addDep(this)
    }
  }

  // 定義notify方法,通知更新
  notify () {
    // 調用每個訂閱者的update方法實現更新
    // stabilize the subscriber list first
    const subs = this.subs.slice()
    for (let i = 0, l = subs.length; i < l; i++) {
      subs[i].update()
    }
  }
}

// Dep.target用來存放目前正在評估的watcher
// 全局唯一,並且一次也只能有一個watcher被評估
// 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
// targetStack用來存放watcher棧
const targetStack = []

// 定義並導出pushTarget函數,接受Watcher類型的參數
export function pushTarget (_target: ?Watcher) {
  // 入棧並將當前watcher賦值給Dep.target
  if (Dep.target) targetStack.push(Dep.target)
  Dep.target = _target
}

// 定義並導出popTarget函數
export function popTarget () {
  // 出棧操作
  Dep.target = targetStack.pop()
}

Watcher

let uid = 0

// watcher用來解析表達式,收集依賴對象,並在表達式的值變動時執行回調函數
// 全局的$watch()方法和指令都以同樣方式實現
/**
 * A watcher parses an expression, collects dependencies,
 * and fires callback when the expression value changes.
 * This is used for both the $watch() api and directives.
 */
// 定義並導出Watcher類
export default class Watcher {
  // 定義變量
  vm: Component; // 實例
  expression: string; // 表達式
  cb: Function; // 回調函數
  id: number; // watcher實例Id
  deep: boolean; // 是否深層依賴
  user: boolean; // 是否用戶定義
  computed: boolean; // 是否計算屬性
  sync: boolean; // 是否同步
  dirty: boolean;  // 是否爲髒監視器
  active: boolean; // 是否激活中
  dep: Dep; // 依賴對象
  deps: Array<Dep>; // 依賴對象數組
  newDeps: Array<Dep>; // 新依賴對象數組
  depIds: SimpleSet;  // 依賴id集合
  newDepIds: SimpleSet; // 新依賴id集合
  before: ?Function; // 先行調用函數
  getter: Function; // 指定getter
  value: any; // 觀察值

  // 定義構造函數
  // 接收vue實例,表達式對象,回調函數,配置對象,是否渲染監視器5個參數
  constructor (
    vm: Component,
    expOrFn: string | Function,
    cb: Function,
    options?: ?Object,
    isRenderWatcher?: boolean
  ) {
    // 下面是對實例屬性的賦值
    this.vm = vm
    // 如果是渲染監視器則將它賦值給實例的_watcher屬性
    if (isRenderWatcher) {
      vm._watcher = this
    }
    // 添加到vm._watchers數組中
    vm._watchers.push(this)
    // 如果配置對象存在,初始化一些配置屬性
    // options
    if (options) {
      this.deep = !!options.deep
      this.user = !!options.user
      this.computed = !!options.computed
      this.sync = !!options.sync
      this.before = options.before
    } else {
      // 否則將配屬性設爲false
      this.deep = this.user = this.computed = this.sync = false
    }
    this.cb = cb
    this.id = ++uid // uid for batching
    this.active = true
    this.dirty = this.computed // for computed watchers
    this.deps = []
    this.newDeps = []
    this.depIds = new Set()
    this.newDepIds = new Set()
    this.expression = process.env.NODE_ENV !== 'production'
      ? expOrFn.toString()
      : ''
    // 設置監視器的getter方法
    // parse expression for getter
    // 如果傳入的expOrFn參數是函數直接賦值給getter屬性
    if (typeof expOrFn === 'function') {
      this.getter = expOrFn
    } else {
      // 否則解析傳入的表達式的路徑,返回最後一級數據對象
      // 這裏是支持使用點符號獲取屬性的表達式來獲取嵌套需觀測數據
      this.getter = parsePath(expOrFn)
      // 不存在getter則設置空函數
      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
        )
      }
    }
    // 如果是計算屬性,創建dep屬性
    if (this.computed) {
      this.value = undefined
      // 
      this.dep = new Dep()
    } else {
      // 負責調用get方法獲取觀測值
      this.value = this.get()
    }
  }

  // 評估getter,並重新收集依賴項
  /**
   * Evaluate the getter, and re-collect dependencies.
   */
  get () {
    // 將實例添加到watcher棧中
    pushTarget(this)
    let value
    const vm = this.vm
    // 嘗試調用vm的getter方法
    try {
      value = this.getter.call(vm, vm)
    } catch (e) {
      // 捕捉到錯誤時,如果是用戶定義的watcher則處理異常
      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方法遞歸每一個對象,將對象的每級屬性收集爲深度依賴項
        traverse(value)
      }
      // 執行出棧
      popTarget()
      // 調用實例cleanupDeps方法
      this.cleanupDeps()
    }
    // 返回觀測數據
    return value
  }

  // 添加依賴
  /**
   * Add a dependency to this directive.
   */
  // 定義addDep方法,接收Dep類型依賴實例對象
  addDep (dep: Dep) {
    const id = dep.id
    // 如果不存在依賴,將新依賴對象id和對象添加進相應數組中
    if (!this.newDepIds.has(id)) {
      this.newDepIds.add(id)
      this.newDeps.push(dep)
      // 並在dep對象中添加監視器自身
      if (!this.depIds.has(id)) {
        dep.addSub(this)
      }
    }
  }

  // 清理依賴項集合
  /**
   * Clean up for dependency collection.
   */
  // 定義cleanupDeps方法
  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   .
   * Will be called when a dependency changes.
   */
  // 定義update方法
  update () {
    // 如果是計算屬性
    /* istanbul ignore else */
    if (this.computed) {
      // 計算屬性的觀察有兩種模式:懶模式和立即模式
      // 默認都設置爲懶模式,要使用立即模式需要至少有一個訂閱者,
      // 典型情況下是另一個計算屬性或渲染函數
      // A computed property watcher has two modes: lazy and activated.
      // It initializes as lazy by default, and only becomes activated when
      // it is depended on by at least one subscriber, which is typically
      // another computed property or a component's render function.
      // 當不存在依賴列表
      if (this.dep.subs.length === 0) {
        // 設置dirty屬性爲true,這是因爲在懶模式下只在需要的時候才執行計算,
        // 所以爲了稍後執行先把dirty屬性設置成true,這樣在屬性被訪問的時候
        // 纔會執行真實的計算過程。
        // In lazy mode, we don't want to perform computations until necessary,
        // so we simply mark the watcher as dirty. The actual computation is
        // performed just-in-time in this.evaluate() when the computed property
        // is accessed.
        this.dirty = true
      } else {
        // 在立即執行模式中,需要主動執行計算
        // 但只在值真正變化的時候才通知訂閱者
        // In activated mode, we want to proactively perform the computation
        // but only notify our subscribers when the value has indeed changed.
        // 調用getAndInvoke函數,判斷是否觀測值真正變化,併發布更新通知
        this.getAndInvoke(() => {
          this.dep.notify()
        })
      }
    } else if (this.sync) {
      // 如果同步執行,則調用實例run方法
      this.run()
    } else {
      // 否則將監視器添加進待評估隊列
      queueWatcher(this)
    }
  }

  // 調度工作接口,會被調度器調用
  /**
   * Scheduler job interface.
   * Will be called by the scheduler.
   */
  // 定義run方法
  run () {
    // 如果當前監視器處於活躍狀態,則立即調用getAndInvoke方法
    if (this.active) {
      this.getAndInvoke(this.cb)
    }
  }

  // 定義getAndInvoke方法,接收一個回調函數參數
  getAndInvoke (cb: Function) {
    // 獲取新觀測值
    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
    ) {
      // 更細觀測值,並設置置否dirty屬性
      // set new value
      const oldValue = this.value
      this.value = value
      this.dirty = false
      // 如果是用戶自定義監視器,則在調用回調函數時設置錯誤捕捉
      if (this.user) {
        try {
          cb.call(this.vm, value, oldValue)
        } catch (e) {
          handleError(e, this.vm, `callback for watcher "${this.expression}"`)
        }
      } else {
        cb.call(this.vm, value, oldValue)
      }
    }
  }

  // 評估和返回觀測值方法,只在計算屬性時被調用
  /**
   * Evaluate and return the value of the watcher.
   * This only gets called for computed property watchers.
   */
  // 定義evaluate方法
  evaluate () {
    // 如果是計算屬性,獲取觀測是,並返回
    if (this.dirty) {
      this.value = this.get()
      this.dirty = false
    }
    return this.value
  }

  // 建立監視器的依賴方法,只在計算屬性調用
  /**
   * Depend on this watcher. Only for computed property watchers.
   */
  // 定義depend方法
  depend () {
    // 如果依賴對象存在且存在當前運行監視器,建立依賴
    if (this.dep && Dep.target) {
      this.dep.depend()
    }
  }

  // 銷燬監視器方法,將自身從依賴數組中移除
  /**
   * Remove self from all dependencies' subscriber list.
   */
  // 定義teardown方法
  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.
      // 當實例正常運行中,從監視器列表中移除監視器
      if (!this.vm._isBeingDestroyed) {
        remove(this.vm._watchers, this)
      }
      // 從所有依賴列表中移除該監視器
      let i = this.deps.length
      while (i--) {
        this.deps[i].removeSub(this)
      }
      // 將監視器的活躍狀態置否
      this.active = false
    }
  }
}

本篇主要是關於源碼的解釋,可以翻看觀察系統的原理篇來對照理解。


在這裏記錄下了Vue的數據綁定具體實現的源代碼的個人理解,有些細節的地方或許還認識的不夠充分,觀察系統裏的三個類兜兜轉轉,關聯性很強,在各自的方法中交叉地引用自身與其他類的實例,很容易讓人頭暈目眩,不管怎樣,對於整體功能邏輯有清晰的認識,以後便能向更高層面邁進。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章