javascriptknockout.jsobservablecomputed-observable

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


I have a particular knockout observable that's used in many computed functions and it works exactly as it's supposed to. However on one of these computed functions I do NOT want it to trigger when the observable is updated. Code wise it would look 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 do still need to be able to access the current value of obs2 when comp2 is executed I just dont want the update of obs2 to trigger comp2 to have a new value.

Is this possible?


Solution

  • To make it ignore updates to an observable, use peek (docs):

    The peek function lets you access an observable or computed observable without creating a dependency.

    Updated example:

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