Messaging with KnockoutJs

Posted by Aligned on Geeks with Blogs See other posts from Geeks with Blogs or by Aligned
Published on Wed, 28 Nov 2012 15:59:18 GMT Indexed on 2012/11/28 17:06 UTC
Read the original article Hit count: 244

Filed under:

MVVM Light has Messaging that helps keep View Models decoupled, isolated, and keep the separation of concerns, while allowing them to communicate with each other. This is a very helpful feature. One View Model can send off a message and if anyone is listening for it, they will react, otherwise nothing will happen. I now want to do the same with KnockoutJs View Models.

Here are some links on how to do this:

http://stackoverflow.com/questions/9892124/whats-the-best-way-of-linking-synchronising-view-models-in-knockout

http://www.knockmeout.net/2012/05/using-ko-native-pubsub.html ~ this is a great article describing the ko.subscribable type.

http://jsfiddle.net/rniemeyer/z7KgM/ ~ shows how to do the subscription

https://github.com/rniemeyer/knockout-postbox will be used to help with the PubSub (described in the blog post above) through the Nuget package.

http://jsfiddle.net/rniemeyer/mg3hj/ of knockout-postbox

 

Implementation:

Use syncWith for two-way synchronization.

MainVM:
self.selectedElement= ko.observable().syncWith (“selectedElement”);

ElementListComponentVM example:
self.selectedElement= ko.observable().syncWith(“selectedElement”);

ko.selectedElement.subscribe(function(){
// do something with the seletion change
});

ElementVMTwo:
self.selectedElement= ko.observable().syncWith (“selectedElement”);

// subscribe example

ko.postbox.subscribe(“changeMessage”, function(newValue){

});

// or use subscribeTo

this.visible = ko.observable().subscribeTo("section", function(newValue) {
// do something here
});

· Use ko.toJS to avoid both sides having the same reference (see the blog post).

· unsubscribeFrom should be called when the dialog is hidden or closed

· Use publishOn to automatically send out messages when an observable changes

o ko.observable().publishOn(“section”);

© Geeks with Blogs or respective owner