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的資料繫結具體實現的原始碼的個人理解,有些細節的地方或許還認識的不夠充分,觀察系統裡的三個類兜兜轉轉,關聯性很強,在各自的方法中交叉地引用自身與其他類的例項,很容易讓人頭暈目眩,不管怎樣,對於整體功能邏輯有清晰的認識,以後便能向更高層面邁進。