我有一个用于许多计算函数的特定 knockout 可观察对象,它的工作方式完全符合预期。但是,在这些计算函数之一上,我不希望它在更新可观察对象时触发。代码明智它看起来像这样:
self.obs1 = ko.observable(foo);
self.obs2 = ko.observable(bar);
//I want this computed to behave normally
this.comp1 = ko.computed(function() {
return self.obs1() + self.obs2();
}, this);
//I want this computed to trigger on obs1 update but ignore updates to obs2
this.comp2 = ko.computed(function() {
return self.obs1() + self.obs2();
}, self);
setTimeout(function() {
self.obs1(20);
self.obs2(15);
}, 1000);
https://jsfiddle.net/r73yLk5u/
请注意,当执行 comp2 时,我仍然需要能够访问 obs2 的当前值,我只是不希望 obs2 的更新触发 comp2 具有新值。
这可能吗?
最佳答案
要使其忽略对可观察对象的更新,请使用 peek
(docs):
The
peek
function lets you access an observable or computed observable without creating a dependency.
更新示例:
//I want this computed to trigger on obs1 update but ignore updates to obs2
this.comp2 = ko.computed(function() {
return self.obs1() + self.obs2.peek();
}, self);
关于javascript - 如何在不触发计算的情况下更新计算中的可观察对象?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40311065/