Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Whats the best way of linking/synchronising view models in Knockout?

If you have several view models on one page, how do you ensure that you can keep them synced? For example, if one item is added or a button clicked on one view model and you want the other view model to be sensitive to that change, can Knockout manage this natively or is it better to use some messaging or pub/sub architecture.

I want to stay away from having to manage observables between models.

like image 984
jaffa Avatar asked Mar 27 '12 14:03

jaffa


People also ask

What is two-way binding in KnockoutJS?

KO is able to create a two-way binding if you use value to link a form element to an Observable property, so that the changes between them are exchanged among them. If you refer a simple property on ViewModel, KO will set the form element's initial state to property value.

What is Knockout used for?

Knockout is a JavaScript library that helps you to create rich, responsive display and editor user interfaces with a clean underlying data model.


1 Answers

Knockout 2.0 does include functionality that lets you do basic pub/sub. Here is a sample where two view models communicate through a mediator.

var postbox = new ko.subscribable();

var ViewModelOne = function() {
    this.items = ko.observableArray(["one", "two", "three"]);
    this.selectedItem = ko.observable();
    this.selectedItem.subscribe(function(newValue) {
        postbox.notifySubscribers(newValue, "selected");
    });
};

var ViewModelTwo = function() {
    this.content = ko.observable();
    postbox.subscribe(function(newValue) {
        this.content(newValue + " content");
    }, this, "selected");
};

ko.applyBindings(new ViewModelOne(), document.getElementById("choices"));
ko.applyBindings(new ViewModelTwo(), document.getElementById("content"));

The first view model notifies through the postbox on a specific topic and the second view model subscribes to that topic. They have no direct dependency on each other.

Certainly the postbox would not need to be global and could be passed into the view model constructor functions or just created inside a self-executing function.

Sample: http://jsfiddle.net/rniemeyer/z7KgM/

Also, the postbox could just be a ko.observable (which includes the ko.subscribable functions).

like image 100
RP Niemeyer Avatar answered Sep 16 '22 19:09

RP Niemeyer