knockout源碼分析之computed(依賴屬性)

1、序列圖

2、主要代碼文件

一、dependentObservable.js:主要包含ko.computed相關方法的處理
二、dependencyDetection.js:主要包含依賴的監控上下文對象。app

3、主要邏輯

一、首先爲某個屬性定義 一個computed對象,以下源碼:
less

var vModel = function(){
        this.fName = ko.observable('fName'),
        this.lName= ko.observable('lName'),
        this.name= ko.computed(function () { //監控依賴對象
            return this.fName() + '-' + this.lName();
        },this);
    };
二、當代碼在執行ko.computed方法,求值方法被做爲參數傳入,並賦值給options的read屬性
三、建立一個state字面量對象,其中包含read、write屬性,以下代碼:
var state = {
        latestValue: undefined,
        isStale: true,
        isBeingEvaluated: false,
        suppressDisposalUntilDisposeWhenReturnsFalse: false,
        isDisposed: false,
        pure: false,
        isSleeping: false,
        readFunction: options["read"],
        evaluatorFunctionTarget: evaluatorFunctionTarget || options["owner"],
        disposeWhenNodeIsRemoved: options["disposeWhenNodeIsRemoved"] || options.disposeWhenNodeIsRemoved || null,
        disposeWhen: options["disposeWhen"] || options.disposeWhen,
        domNodeDisposalCallback: null,
        dependencyTracking: {},
        dependenciesCount: 0,
        evaluationTimeoutInstance: null
    };
四、生成computedObservable對象(function),而後將state附加到_state屬性上,則擴展爲發佈/訂閱對象。
五、擴展computedFn全部方法和屬性到computedObservable對象上
// Inherit from 'subscribable'
    if (!ko.utils.canSetPrototype) {
        // 'subscribable' won't be on the prototype chain unless we put it there directly
        ko.utils.extend(computedObservable, ko.subscribable['fn']);
    }
    ko.subscribable['fn'].init(computedObservable); //執行發佈/訂閱對象的init方法,用於初始化發佈/訂閱對象。

    // Inherit from 'computed'
    ko.utils.setPrototypeOfOrExtend(computedObservable, computedFn);
六、而後執行computedObservable的evaluateImmediate方法,此方法中最重的三點:
   6.一、在evaluateImmediate_CallReadWithDependencyDetection方法中,建立了依賴監控對象,並添加到依賴監控上下文中
var isInitial = state.pure ? undefined : !state.dependenciesCount,   // If we're evaluating when there are no previous dependencies, it must be the first time
            dependencyDetectionContext = {
                computedObservable: computedObservable,
                disposalCandidates: state.dependencyTracking,
                disposalCount: state.dependenciesCount
            };

        ko.dependencyDetection.begin({
            callbackTarget: dependencyDetectionContext,
            callback: computedBeginDependencyDetectionCallback,
            computed: computedObservable,
            isInitial: isInitial
        });
    6.二、而後調用evaluateImmediate_CallReadThenEndDependencyDetection方法,參數傳遞的state(在ko.computed方法中定義的)、dependencyDetectionContext(依賴監控對象)
    6.三、其中用到了try catch finall方式,確保ko.dependencyDetection.end方法的執行
try {
            var readFunction = state.readFunction;
            return state.evaluatorFunctionTarget ? readFunction.call(state.evaluatorFunctionTarget) : readFunction();
        } finally {
            ko.dependencyDetection.end();

            // For each subscription no longer being used, remove it from the active subscriptions list and dispose it
            if (dependencyDetectionContext.disposalCount && !state.isSleeping) {
                ko.utils.objectForEach(dependencyDetectionContext.disposalCandidates, computedDisposeDependencyCallback);
            }

            state.isStale = false;
        }
七、在執行ko.computed的readFunction方法時,其中就執行了ko.observable方法(執行的是read),這時就會去調用ko.dependencyDetection.registerDependency方法(參數爲此函數對象)
function observable() {
        if (arguments.length > 0) {
            // Write

            // Ignore writes if the value hasn't changed
            if (observable.isDifferent(observable[observableLatestValue], arguments[0])) {
                observable.valueWillMutate();
                observable[observableLatestValue] = arguments[0];
                observable.valueHasMutated();
            }
            return this; // Permits chained assignments
        }
        else {
            debugger;
            // Read
            ko.dependencyDetection.registerDependency(observable); //執行依賴
            return observable[observableLatestValue];
        }
    }
八、在ko.dependencyDetection中的registerDependency方法內,首先會判斷ko.observable是否爲訂閱對象,若是是則執行begin加入的callbak函數.
registerDependency: function (subscribable) { //注入到相關依賴屬性
            if (currentFrame) {
                if (!ko.isSubscribable(subscribable))
                    throw new Error("Only subscribable things can act as dependencies");
                currentFrame.callback.call(currentFrame.callbackTarget, subscribable, subscribable._id || (subscribable._id = getId()));
            }
        }
九、執行evaluateImmediate方法後,而後註冊Dom移除回調事件。
if (state.disposeWhenNodeIsRemoved && computedObservable.isActive()) {
        ko.utils.domNodeDisposal.addDisposeCallback(state.disposeWhenNodeIsRemoved, state.domNodeDisposalCallback = function () {
            computedObservable.dispose();
        });
    }
十、返回computedObservable對象

4、補充說明

一、ko.dependencyDetection中有ignore方法,他主要實現的是一個異步鎖,讓callbcak處於鎖的狀態執行
dom

ignore: function (callback, callbackTarget, callbackArgs) { //按順序s執行依賴,但不觸發訂閱。
            try {
                begin();
                return callback.apply(callbackTarget, callbackArgs || []);
            } finally {
                end();
            }
        }
二、ko.computed 與 ko.dependentObservable是相同的。
相關文章
相關標籤/搜索