Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Difference between isObservable and isSubscribable

Tags:

knockout.js

Seems they return the same result, why use one over the other?

var computed = ko.computed(function(){return 'foo';});
var observable  = ko.observable();
var observableArray  = ko.observableArray();

console.log('computed isObservable', ko.isObservable(computed));
console.log('observable isObservable', ko.isObservable(observable));
console.log('observableArray isObservable', ko.isObservable(observableArray));

console.log('computed isSubscribable', ko.isSubscribable(computed));
console.log('observable isSubscribable', ko.isSubscribable(observable));
console.log('observableArray isSubscribable', ko.isSubscribable(observableArray));

All log true. http://jsfiddle.net/1fvjuj9v/1/

like image 438
Martin Hansen Avatar asked Apr 28 '15 08:04

Martin Hansen


1 Answers

So a subscribable is a knockout object, different from observables or computeds, but that both observables and computeds inherit from. A subscribable is anything that can be subscribed to; anything that can emit events which other parts of the code can listen to. It's where the observable.subscribe(function() {}) functionality is derived from.

An observable, on the other hand, is a specific type of a subscribable: it's a subscribable that holds a value and that emits the new value to its subscribers whenever that value changes. The "has a current value" part of the observable isn't an inherent part of being a "subscribable", only the "emits events to its subscribers" part is.

It's not used much, but you can construct subscribables directly, and they will pass the ko.isSubscribable test but fail the ko.isObservable test, hence the difference between those two methods.

Though I personally haven't seen it done in practice, this blog post gives an example of how you might make use of or extend the ko.subscribable functionality, by building a Pub/Sub interface on top of subscribables.

The relation is illustrated by this chart from the knockout documentation on custom functions. Chart displaying the relation between


Note, however, that the above chart is a bit deceptive on one point: ko.computed actually derives from ko.observable not from ko.subscribable directly. Hence why ko.isObservable(computed) returns true. However the relation indicated by the chart is the relation used for inheriting custom functions added to knockout objects. (Which makes sense, given that was the topic of the page of the documentation it was found on)

So if you define a custom function on ko.subscribable.fn, then it will be available both on computeds and on observables... but if you define one on ko.observable.fn it'll only be available on observables (and observable arrays) not on computeds, despite the fact that ko.isObservable(computed) returns true.

like image 200
Retsam Avatar answered Sep 28 '22 09:09

Retsam