嗨有没有办法在实例化ko.computed
时触发该函数示例是
我有这个ko.computed
ko.computed(function(){ alert(this.Test); } , this);
所以基本上如果我实例化这个计算,这将触发那里定义的函数 有没有办法在实例化时解雇它?并且只有在依赖性改变时才激活它?
答案 0 :(得分:4)
您需要设置deferEvaluation
option:
deferEvaluation
- 可选。如果此选项为true
,则在实际尝试访问其值或手动订阅它之前,不会计算计算的observable的值。默认情况下,计算的observable在创建过程中会立即确定其值。
ko.computed(function(){ alert(this.Test); } , this, { deferEvaluation: true });
答案 1 :(得分:3)
你也可以使用淘汰赛pureComputed
。纯计算仅在存在依赖时评估。
示例:
var person, fullName,
getFullName = function() {
return person().firstName() + " " + person().lastName();
};
person = ko.observable(null);
// This won't work, because the computed evaluates and getFullName doesn't
// check for `null`
try {
fullName = ko.computed(getFullName);
} catch (err) {
console.log("Regular computed:");
console.log(err.message);
}
// This will work because there's no dependency to `fullName` yet
// At `applyBindings`, `fullName` needs to be evaluated
fullName = ko.pureComputed(getFullName);
person({
firstName: ko.observable("Jane"),
lastName: ko.observable("Doe")
});
ko.applyBindings({ heading: fullName })
<script src="https://cdnjs.cloudflare.com/ajax/libs/knockout/3.4.2/knockout-min.js"></script>
<h3 data-bind="text: heading"></h3>