KRISHNA VADIVELU
KRISHNA VADIVELU

Reputation: 31

How to know source of computed observable

When computed observable depends on many other observables, how to know which observable change triggered this computed observable's eval function?

Upvotes: 0

Views: 176

Answers (2)

300 baud
300 baud

Reputation: 1672

You could track changes to the observables by using KO extenders. First, you have to create the extender function. Here is a super simple one that simply adds a flag to the observable if it has changed.

ko.extenders.changeTracker = function(target, trackingPropertyName) {
  target.subscribe(function(value) {
    target[trackingPropertyName] = true;
  });
  return target;
}

Then you would have to add this extender to the observable being tracked. The trackingPropertyName would be used to read and write the change tracking flag.

var trackingPropertyName = '__mytracker';
this.firstName = ko.observable().extend({ changeTracker: trackingPropertyName });
this.lastName = ko.observable().extend({ changeTracker: trackingPropertyName });

Within your computed you would evaluate these flags (and reset them) to determine which observable has changed.

this.fullName = ko.pureComputed(function() {
  var f = this.firstName() || '';
  var l = this.lastName() || '';
  if (this.firstName[trackingPropertyName]) {
    // firstName changed code here -- plus reset the flag
    this.firstName[trackingPropertyName] = false;
  }
  if (this.lastName[trackingPropertyName]) {
    // lastName changed code here -- plus reset the flag
    this.lastName[trackingPropertyName] = false;
  }
  return f + ' ' + l;
}, this);

Here is a Fiddle: https://jsfiddle.net/8so7zjy5

Or an ES5-friendly version: https://jsfiddle.net/8so7zjy5/1/

Upvotes: 0

Jeroen
Jeroen

Reputation: 63830

It's impossible to find out what triggered a computed's change.

The relevant source file is actually quite easy to follow, and if you dig into it you'll see that a computed (a.k.a. dependentObservables) can have a change triggered from a number of sources. Heck, by the time the actual change notification goes out, multiple asynchronous calls to dependencies might have caused the change. None of that info is exposed to users of the KO library.

If you find yourself wanting this, you'll need to rethink your approach. Without any details on your context it's impossible to offer more specific advise though.

Upvotes: 3

Related Questions