The ViewModels, Models and Collections have the ability to publish and subscribe to messages. The API looks like this:
var MyViewModel = ko.ViewModel.extend({
subscriptions: {
'my-topic': function (data) {
alert(data);
}
}
});
var myViewModel = new MyViewModel();
myViewModel.publish('my-topic', 'hello world');
You can pass an object called "subscriptions" into any viewModel, Model or Collection. The name will be the topic that is listened for and the argument will be the callback function when the topic is published.
Subscribes the ViewModel, Model or Collection to a topic.
this.subscribe('my-topic', function () {
...
});
Publishes the data to everywhere that is subscribed to the topic.
this.publish('my-topic', {
...
});
Unsubscribes the ViewModel, Model or Collection from the topic that is passed in.
this.unsubscribe('my-topic');
Removes all of the subscriptions on the ViewModel, Model or Collection.
this.unsubscribeAll();