Difference between subscribe and computed in knockout js

In short, a computed is reasonably like a getter/setter property and mainly for calculated values. Subscribe may be a kind of recall perform that you will add/remove from a subscribable object, which observables and computeds derive from.

By default, a subscription subscribes to a topic called ‘change’, and would look like this when expressly defined:

var obsType = ko.observable();
obsType.subscribe(function(newValue) { ... }, null, 'change')

There is another inbuilt topic you’ll be able to buy referred to as ‘beforeChange’ and therefore the price passed in is the recent value:

obsType.subscribe(function(oldValue) { ... }, null, 'beforeChange');

You can also produce your own custom topics to observe and ‘publish’ to if you need, something like this

obsType.subscribe(function(newValue) { ... }, null, 'customTopic');
obsType("Hello World");// When this updates, 'change' and 'beforeChange' subscriptions are called.
obsType.notifySubscribers('customTopic');

1 thought on “Difference between subscribe and computed in knockout js

Author gravatar
ig August 4, 2017, 12:37 am

I don’t even know how I ended up here, but I thought this post was great.
I do not know who you are but certainly you
are going to a famous blogger if you are not already 😉 Cheers!

Leave a Reply

Your email address will not be published. Required fields are marked *