this.x = ko.observable(); this.y = ko.observable(); this.updated = ko.observable(false); this.tracker = ko.computed(function() { this.x(); this.y(); this.updated(true); }, this);
The tracker function is equivalent to
var callback = function() { this.updated(true); }); this.x.subscribe(callback, this); this.y.subscribe(callback, this);
The pattern with ko.computed is compact and elegant. A single function tracks multiple observables, and fires an event when one of the tracked observables changes.
My challenge with this pattern is the readability, though. A non-expert KnockoutJS user may have a hard time figuring out what's going on because the intent is not obvious from the code. The pattern is exactly the opposite of basic ko.observable usage. Simple cases like "fullName = firstName + lastName" use the tracked observables to calculate and return an output, and have no other side effect. In this case, the tracked observables' values aren't used, there is no output, and there are side effects.
On the other hand, a KO expert who understands how ko.computed tracks observables might find this pattern is more readable than the alternative.
So I'm thinking, it's ok to use this pattern, but with some conventions to help prevent beginners from getting too confused. Some thoughts:
- Use a naming convention to distinguish this ko.computed pattern from others. For example, onSomethingChanged or trackSomething. This way the name sounds like an event listener.
- Don't mix the ko.computed patterns - either return a value or have a side effect, but not both
- Within the ko.computed body, make a clear separation between setting up observable tracking and the action to fire when something changes.
- Consider separating the code comments - this is one of those times when code comments are helpful to explain something that might not be obvious from the code itself.
For example:
this.onInputChanged = ko.computed(function() { var trackedObservables = [this.x(), this.y()]; // action when one of trackedObservables changes this.updated(true); }, this);
KO documentation on computeds: http://knockoutjs.com/documentation/computedObservables.html