1
votes

I have two view models in Knockout.js and I am aware that i can bind them separately, however is it possible for me to add them both in a Master View Model and bind it once. Something like ko.applyBindingings(MasterViewModel); Any help or advice is much appreaciated. Thanks a ton.

  var ViewModel1 = {
        id: ko.observable(""),
        name: ko.observable("")}

var ViewModel2 = {
        id: ko.observable(""),
        name: ko.observable("")}

Right now I bind it as folllows: ko.applyBindings(ViewModel1 , document.getElementById('div1')); ko.applyBindings(ViewModel2 , document.getElementById('div2'));

3

3 Answers

1
votes

Sure thing. In your JavaScript:

 MasterViewModel = function() {
    this.ViewModel1 = {
      id: ko.observable(""),
      name: ko.observable("")
    }

    this.ViewModel2 = {
      id: ko.observable(""),
      name: ko.observable("")
    }
 }
 ko.applyBindings(new MasterViewModel(), document.getElementById('masterDiv'));

In your HTML Markup:

 <div id="masterDiv">
    <div id="div1">
        <strong data-bind="text: ViewModel1.name"/>
    </div>
    <div id="div2">
        <strong data-bind="text: ViewModel2.name"/>
    </div>
 </div>

You'll have to reference your ViewModels by name in your data-binding markup. This allows you to determine which ViewModel's properties to bind to.

1
votes

The other answer (@PatrickD) is correct except it has syntax errors. The MasterViewModel is an object literal so it should be written like this:

var MasterViewModel = {
    ViewModel1 : {
      id: ko.observable(""),
      name: ko.observable("")
    },
    ViewModel2 : {
      id: ko.observable(""),
      name: ko.observable("")
    }
 };
-1
votes
var MasterViewModel = {
    var ViewModel1 = {
      id: ko.observable(""),
      name: ko.observable("")
    }

    var ViewModel2 = {
      id: ko.observable(""),
      name: ko.observable("")
    }
 }

 ko.applyBindings(new MasterViewModel(), document.getElementById('masterDiv');

You could also simplify your markup by using the with binding

<div id="masterDiv">
    <div data-bind="with: ViewModel1">
         <strong data-bind="text: name"/>
    </div>

    <div data-bind="with: ViewModel2">
        <strong data-bind="text: name"/>
    </div>
</div>