postbox

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

by adrienne

HTML

<script src="https://github.com/downloads/SteveSanderson/knockout/knockout-2.0.0.debug.js"></script>
<div id="choices">
   <ul data-bind="foreach: items">
       <li>
           <a href="#" data-bind="text: $data, click: $root.selectedItem"></a> 
       </li>
    </ul>
</div>

<hr/>
               
<div id="content">
    <div data-bind="text: content"></div>
</div>

CSS

#choices li { display: inline; margin: 5px; }

JavaScript

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"));