Geeks With Blogs

News profile for Aligned at Stack Overflow, Q&A for professional and enthusiast programmers

Donate Bitcoins

Check out Elapser from T3rse!
"free in Christ Jesus from the law of sin and death." Romans 8:2 (ESV) Check out the Falling Plates video on YouTube.
more about the Gospel
And then listen to Francis Chan speaking at LifeLight in SD.

Programming and Learning from SD

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 using knockout-postbox:

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 selection 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”);

Posted on Wednesday, November 28, 2012 9:59 AM Knockout Js | Back to top


Comments on this post: Messaging with KnockoutJs

# re: Messaging with KnockoutJs
Requesting Gravatar...
Awesome! I always use amplify.js for pub-sub. I didn't know it was built in to KO.
Left by Ryan on Nov 29, 2012 1:59 PM

Your comment:
 (will show your gravatar)


Copyright © Aligned | Powered by: GeeksWithBlogs.net | Join free