Mobx——computed 裝飾器的實現(xiàn)原理 (離職拷貝版)

離職了,把 2019 年在公司寫的文檔 copy 出來。年頭有點久,可能寫的不太對,也不是很想改了~
注:本文檔對應(yīng) mobx 版本為 4.15.4、mobx-vue 版本為 2.0.10

對比 Vue 的猜想

Vue computed 的實現(xiàn)邏輯

  1. initComputed:遍歷 option.computed 建立 Watcher, 然后執(zhí)行 defineComputed
  2. new Watcher(vm, getter || noop, noop, computedWatcherOptions),初始化對應(yīng)的 watcher,Watcher 的四個參數(shù)為 vm 實例、 computed 的行為函數(shù)(也就是根據(jù) computed的格式拿到執(zhí)行函數(shù))、 noop、 和默認的computedWatcherOptions: { lazy: true }
  3. defineComputed(target, key, userDef),對應(yīng)三個參數(shù)為 vm 實例、計算屬性的key值、計算屬性的對應(yīng)的執(zhí)行函數(shù)
    a. 定義sharedPropertyDefinition,sharedPropertyDefinition.get = createComputedGetter(key),sharedPropertyDefinition.set = noop;
    b. 其中 createComputedGetter
function createComputedGetter (key) {
    return function computedGetter () {
        var watcher = this._computedWatchers && this._computedWatchers[key];
        if (watcher) {
            if (watcher.dirty) {
                watcher.evaluate();
            }
            if (Dep.target) {
                watcher.depend();
            }
            return watcher.value
        }
    }
}

c. 執(zhí)行 Object.defineProperty(target, key, sharedPropertyDefinition);

值得注意的是 computed 的 Watcher 傳進去的 option 為 lazy: true

這也就意味著在派發(fā)更新階段,雖然你 Watcher 被 notify 了,但是并不會被執(zhí)行下去,而是在主 Watcher 執(zhí)行了他自己的 run -> get -> getter -> vm._updata => vm._render 過程中,在最后的 _render 里觸發(fā)到了 computed 的 getter,這時候才會涉及到 computed 屬性的計算并賦一個新值。 用原子更新—— value 和 計算屬性 squared 以及 計算屬性 cubic 的例子講解具體流程如下:

  1. 改變 value 的值
  2. Dep.notify 遍歷 Dep 下面的 Watcher 數(shù)組(相關(guān)依賴的 Watcher ), 執(zhí)行各自的 updata,這個案例中涉及到 Dep 下面的3個 Watcher 分別是,value 對應(yīng)的 vm 雙向綁定的 Watcher、計算屬性 squared 的 Watcher、計算屬性 cubic 的 Watcher,
  3. updata 就是 lazy 啥也不干,不 lazy 的如果是同步則執(zhí)行 run / 異步走 queueWatcher 攢一波然后再 run,run 就是執(zhí)行 get,get 就是執(zhí)行 getter,這里因為 computed 是 lazy 所以只走了主 Watcher,來執(zhí)行 vm._update。那些 lazy 的 getter 就是你定義計算屬性傳進去的那個函數(shù),然后把返回值付給 Wathcer 的 value,只是一個賦值過程,
  4. 最后在 render 過程中,需要使用 computed 的變量,觸發(fā)到 computed 的 get,因為在 Watcher.updata 的時候 dirty 被置成了 true,所以在上述 3.b 中執(zhí)行 evaluate ,evaluate 干了兩件事:this.value = this.getter(); this.dirty = false,然后返回 watcher.value,即計算后的平方和立方

Vue watch 的實現(xiàn)邏輯

其實和 mobx 的 @computed 沒啥聯(lián)系,但在 Vue 里 computed 和 watch 還是有比較通用的使用場景的,順便追下源碼,看看 watch 和 computed 的區(qū)別。

還是上面那個平方和立方的例子,如果用 watch 來做,就需要額外定義兩個 data,然后 watch 了之后改變其對應(yīng)的值,這么寫的話,會產(chǎn)生額外 2 個 Dep,也就是 squared 的依賴項和 cubic 的依賴項,源碼差不多都是一個意思,都得 new 一個 Watcher,只不過響應(yīng)式的實現(xiàn)從計算屬性的渲染時計算 變成了 data 的雙向綁定,先改變值再渲染,具體流程如下:

  1. 改變 value 的值
  2. Dep.notify 遍歷 Dep 下面的 Watcher 數(shù)組(相關(guān)依賴的 Watcher ), 執(zhí)行各自的 updata,這里面會有 3 個 Dep.notify,因為值、平方、立方都變了,各自的 Dep 下面都有渲染視圖的那個主 Watcher,不過 Watcher 有去重功能
  3. 然后就是執(zhí)行平方的 Watcher、 立方的 Watcher、 主 Watcher
  4. 最后再 render

如果你好奇 watch 生成的 Wachter 是怎么和 Dep 建立關(guān)系的,可以看下 Watcher 里 getter 的定義:

this.getter = parsePath(expOrFn); // 這里expOrFn 就是你定義的回調(diào)函數(shù)

function parsePath (path) {
    if (bailRE.test(path)) {
        return
    }
    var segments = path.split('.');
    return function (obj) {
        for (var i = 0; i < segments.length; i++) {
            if (!obj) { return }
                obj = obj[segments[i]];
        }
        return obj
    }
}

在首次依賴收集的時候 Watcher.get 會執(zhí)行 value = this.getter.call(vm, vm);這時候 vm 被扔進去,正好觸發(fā)了依賴項 data.value 的 get,然后 dep 和 Watcher 的依賴關(guān)系被建立

源碼解析

其實這里和 @observable 會執(zhí)行幾乎一樣的裝飾器邏輯。少一層 createDecoratorForEnhancer,最后執(zhí)行的是 addComputedProp,而不是addObservableProp

  1. createPropDecorator
const computed: IComputed = function computed(arg1, arg2, arg3) {
    if (typeof arg2 === "string") {
        // @computed
        return computedDecorator.apply(null, arguments)
    }
    ...
}


const computedDecorator = createPropDecorator(
    false,
    (
        instance: any,
        propertyName: PropertyKey,
        descriptor: any,
        decoratorTarget: any,
        decoratorArgs: any[]
    ) => {
        const { get, set } = descriptor
        const options = decoratorArgs[0] || {}
        // 4版本如下
        defineComputedProperty(instance, propertyName, { get, set, ...options })
        
        // 對應(yīng)5版本的代碼比較直接
        asObservableObject(instance).addComputedProp(instance, propertyName, {
            get,
            set,
            context: instance,
            ...options
        })
    }
)

省去中間相同的邏輯,直接看 defineComputedProperty

  1. defineComputedProperty
function defineComputedProperty(
    target: any,
    propName: string,
    options: IComputedValueOptions<any>
) {
    const adm = asObservableObject(target)
    options.name = `${adm.name}.${propName}`
    options.context = target
    adm.values[propName] = new ComputedValue(options)
    Object.defineProperty(target, propName, generateComputedPropConfig(propName))
}

和上面稍微有些不同,但是核心邏輯都一樣,拿到 ObservableObjectAdministration,然后往 value 上面掛東西,只不過這里掛的是 ComputedValue 而不是 ObservableValue

  1. generateComputedPropConfig
function generateObservablePropConfig(propName) {
    return (
        observablePropertyConfigs[propName] ||
        (observablePropertyConfigs[propName] = {
            configurable: true,
            enumerable: true,
            get() {
                return this.$mobx.read(this, propName)
            },
            set(v) {
                this.$mobx.write(this, propName, v)
            }
        })
    )
}

結(jié)論就是和 @observable 差不多的實現(xiàn)流程,也就是想辦法搞一套 get 和 set 邏輯,但是之所以把 Vue 的 computed 和 watch 拉出來講一下,是為了突出 Vue 里面 computed 創(chuàng)建的 Watcher 和一般的 Wathcer 不太一樣,派發(fā)更新的時機和方法也獨樹一幟。反觀 Mobx 的@computed,不僅加不加都行,而且專門弄出來一個和 Reaction(對應(yīng) Vue 的 Watcher) 平級的 ComputedValue,意義就是在 @observable 依賴項發(fā)生變化時,不僅僅要觸發(fā)更新視圖的 Reaction,還要對監(jiān)聽自己的 ComputedValue 進行更新,觸發(fā)的順序也是在 Vue 的 render 之后,但是在 Vue + 全局 mobx 的環(huán)境下有些顯得多余。

舉個例子就是:在我們的項目里如果有一個組件 A 自己維護 @observable valueA,然后他有一個子組件 B, 用 props 傳遞了 valueA,并讓組件 B 的 VM @computed 了一下 valueA,@observable valueA 上只有更新組件 A 的 Reaction,所以 valueA 變化之后組件 B 并不會更新。

但是項目中并沒有這樣的操作,變量都維護在了全局的 Store 中,每個 Vue 都會有 extends BaseVM 的 VM,所以一旦 @observable 發(fā)生變動,所有的組件都會被重新渲染

?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容