Adrian Salazar
Adrian Salazar

Reputation: 5319

KnockoutJS, using subscribable. callbackTarget

I want to implement a simple pub-sub in my application, so KO subscribable seems to be promising.

I have the the following code.

var announcer = new ko.subscribable();

var s1 = announcer.subscribe(function(val){
    console.log('subscriber1: ' + val);
}, null, 'news');

var s2 = announcer.subscribe(function(val){
    console.log('subscriber2: ' + val);
}, null, 'gossip');

var s3 = announcer.subscribe(function(val){
    console.log('subscriber3: ' + val);
}, null, 'news');

Publish in the "news" channel

announcer.notifySubscribers('good news', 'news')

/* Outputs: */

subscriber1: good news
subscriber3: good news 

Publish in the "gossip" channel

announcer.notifySubscribers('hipster news', 'gossip')

/* Outputs: */

subscriber2: hipster news 

So far, it seems to work...

My question is:

What is the second parameter that subscribable.subscribe expects?

Knockout website never speaks about it, so I went to the code and found this:

subscribe: function (callback, callbackTarget, event) {
    event = event || defaultEvent;
    var boundCallback = callbackTarget ? callback.bind(callbackTarget) : callback;

var subscription = new ko.subscription(this, boundCallback, function () {
        ko.utils.arrayRemoveItem(this._subscriptions[event], subscription);
    }.bind(this));

It is obvious that my implementation of pub/sub works because I am not passing a callbackTarget, so callback is used instead.

Bonus questions:

When should we use a callbackTarget?

Can anyone provide an example of its usage?

Upvotes: 4

Views: 3503

Answers (2)

PW Kad
PW Kad

Reputation: 14995

Don't take my word as solemn because I have never used this capability but I believe I can answer your question anyways...

The callbackTarget is the context that you want to bind to, so if you are subscribing from outside your viewmodel you can still bind to that context by passing it in -

When should we use a callbackTarget?

When you are binding to a context outside of that context - ie binding to the context of a viewmodel when you have multiple view models.

Can anyone provide an example of its usage?

Example from - http://www.knockmeout.net/2012/05/using-ko-native-pubsub.html

postbox.subscribe(callback, target, topic);

postbox.subscribe(function(newValue) {
    this.latestTopic(newValue);
}, vm, "mytopic");

Where the function is the callback, the callbackTarget is 'vm', and the topic is 'mytopic'

Upvotes: 1

Artem Vyshniakov
Artem Vyshniakov

Reputation: 16465

The second parameter of subscribe function is used for setting context of this. If do not want to use this inside callback function you can pass null.

Upvotes: 3

Related Questions