【发布时间】:2012-04-26 04:29:17
【问题描述】:
KnockoutJS 有计算 observables 的概念,它是依赖于一个或多个 observables 的函数。淘汰赛可以determine the dependencies of a computed observable as described in the docs:
每当你声明一个计算的 observable 时,KO 立即调用它的 求值函数获取其初始值。当你的评估员 函数正在运行,KO 会记录任何可观察的(或计算的) observables) 你的评估者读取的值。
现在,我不明白的是,如果您的计算 observable 包含条件逻辑,这是如何工作的。如果 Knockout 调用 evaluator 函数,那么条件逻辑肯定会导致函数所依赖的 observables 未被调用?
我创建了这个小提琴来测试:
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 的依赖关系。
谁能解释一下?
【问题讨论】:
-
无法回答问题,我相信计算的 observables 通过评估所有依赖项来确定运行时自己的状态,所以一切看起来都清晰明了,抱歉,但无法得到您问题的重点
-
好问题。我一直认为您引用的手册中描述的方法非常聪明,但是既然您指出了这一点,我想知道它是否非常聪明,而不仅仅是非常聪明...:D
标签: knockout.js