How to update observable during calculation without starting calculations?

I have a specific knockout observable that is used in many computable functions, and it works exactly as intended. However, for one of these calculated functions, I DO NOT want it to work when updating the observable. The wise code looks something like this:

  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/

Note that I still need to have access to the current value of obs2 when comp2 is running. I just don't want the obs2 update to call comp2 for the new value.

Is it possible?

+4
source share
2 answers

, , peek ():

peek .

:

//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/

+2

, , . , , , , rateLimit , , , . obs2, .

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

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

0

Source: https://habr.com/ru/post/1659215/


All Articles