KnockoutJS具有计算的可观察量的概念,它是依赖于一个或多个可观察量的函数。淘汰赛能够 确定计算的observable的依赖关系,如文档中所述:
每当你声明一个计算的observable时,KO立即调用它 求值函数获取其初始值。而你的评估员 函数正在运行,KO记录任何可观察量(或计算出来的) observables)你的评估者读取的值。
现在,我不明白的是,如果你的计算的observable包含条件逻辑,它是如何工作的。如果Knockout调用赋值器函数,肯定条件逻辑可能会导致函数依赖于不被调用的可观察对象?
我创造了这个小提琴来测试:
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);
};
然而,不知何故,Knockout正确地确定了对两者的依赖性 firstName
和 lastName
。
谁能解释一下怎么样?