KnockoutJS - 具有条件语句的计算可观察量如何工作

Col*_*inE 11 knockout.js

KnockoutJS具有计算的可观察量的概念,它是依赖于一个或多个可观察量的函数.Knockout能够确定计算的observable的依赖关系,如文档中所述:

每当您声明一个计算的observable时,KO立即调用其求值函数来获取其初始值.当您的求值程序函数运行时,KO会记录您的求值程序读取值的任何可观察对象(或计算的可观察对象).

现在,我不明白的是,如果你的计算的observable包含条件逻辑,它是如何工作的.如果Knockout调用求值函数,肯定条件逻辑可能会导致函数依赖于不被调用的可观察对象?

我创造了这个小提琴来测试:

http://jsfiddle.net/bJK98/

var ViewModel = function(first, last) {
    this.firstName = ko.observable(first);
    this.lastName = ko.observable(last);
    this.condition = ko.observable(false);

    // at the point of evaluation of this computed observabled, 'condition'
    // will be false, yet the dependecy to both firstName and lastName is
    // identified
    this.fullName = ko.computed(function() {
        return this.condition() ? this.firstName() : this.lastName();
    }, this);
};
Run Code Online (Sandbox Code Playgroud)

然而,不知何故淘汰赛正确识别依赖于两个firstNamelastName.

谁能解释一下怎么样?

RP *_*yer 13

每次重新评估dependentObservable时,都会再次跟踪依赖关系.因此,如果您有条件逻辑,那么未命中的分支将不会对依赖项做出贡献.

在您的小提琴中,如果您编辑firstName,则在切换之前不会更新该值condition.此时,lastName不再是依赖项,因此对它的更改不会触发dependentObservable.

它并不比原始描述复杂得多.要记住的基本事项是每次重新评估依赖关系.