KnockoutJS Multiple ViewModels
by Farzad Cyrus
HTML
<div id="container1">
<input data-bind="value: firstName" /> <input data-bind="value: lastName" />
<p>First name: <strong data-bind="text: firstName"></strong></p>
<p>Last name: <strong data-bind="text: lastName"></strong></p>
</div>
<div id="container2">
<input data-bind="value: firstName" /> <input data-bind="value: lastName" />
<p>First name: <strong data-bind="text: firstName"></strong></p>
<p>Last name: <strong data-bind="text: lastName"></strong></p>
</div>
JavaScript
AppViewModel = {
VM1: new VM1(),
VM2: new VM2()
}
function VM1() {
this.firstName = ko.observable("John");
this.lastName = ko.observable("Smith");
}
function VM2() {
this.firstName = ko.observable("Bob");
this.lastName = ko.observable("Branden");
}
ko.applyBindings(AppViewModel.VM1, document.getElementById("container1"));
ko.applyBindings(AppViewModel.VM2, document.getElementById("container2"));