如何在不触发计算的情况下更新计算中的可观察对象?

How to update an observable in a computed without triggering the computed?

我有一个用于许多计算函数的特定淘汰可观察对象,它完全按照预期工作。但是,在这些计算函数之一上,我不希望它在更新可观察对象时触发。代码明智它看起来像这样:

  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 具有新值。

这可能吗?

好吧,我知道怎么做了。如果你创建一个新的计算,它只 returns 你想要延迟的 observable 然后 rateLimit 它到一个它永远不会命中的点你可以只使用计算来代替 observable。如果将来由于任何其他原因触发计算,这也将使它始终使用最新的 obs2 值。

  self.obs2DelayComp = ko.computed(function() {
    return self.obs2();
  }).extend({ rateLimit: 3001 });

https://jsfiddle.net/r73yLk5u/1/

要使其忽略对可观察对象的更新,请使用 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);

https://jsfiddle.net/r73yLk5u/2/