Habib
Habib

Reputation: 300

Knockout: Prevenet a property from adding into a computed's dependency list

I have an infobox which is either open or closed depending on the value if isVisible property.

self.infoboxState = ko.computed(function () {
     if (!ko.computedContext.isInitial()) {
          self.performAdditionalBehaviors();
     }
     return ko.unwrap(self.isVisible)? 'infobox-open' : 'infobox-closed';
}, this);

When we set the value of isVisible for the second time it would also execute performAdditionalBehaviors() method. This method contains an observable property isDim and the infoboxState becomes dependent on both observables which means any change in the isDim property will also now call the infoboxState. I verified that from getDependenciesCount() which is now set to 2.

The issue is that I don't want infoboxState to get called whenever isDim is changed. Is there any way to tell the computed to not add a property into it's dependencies list?

Upvotes: 0

Views: 98

Answers (1)

Jeff Mercado
Jeff Mercado

Reputation: 134881

If you don't want an observable read within the context of a computed observable to be registered as a dependency, you need to peek() at the value instead of simply reading it.

Controlling dependencies using peek

Furthermore, your performAdditionalBehaviors() should not even be in the computed observable. You want those behaviors to happen if the isVisible property changes, you should be subscribing to it instead.

this.infoboxState = ko.computed(function () {
     return ko.unwrap(this.isVisible)? 'infobox-open' : 'infobox-closed';
}, this);
this.infoboxState.subscribe(function () {
     this.performAdditionalBehaviors();
}, this);

Upvotes: 1

Related Questions