Binding Knockoutjs View Model Using DOM Element ID | Knockout.js


There are scenarios where we have two view models in a single view. In such case, the binding can be done using the ko.applyBindings, adding the DOM element id as the second parameter. To achieve this, we need to wrap the forms (or set of controls) in separate DOM element like<div>. The, set unique element id for each <div> enclosing the controls. 
Use the id as the second parameter for ko.applyBindings and bind the view models separately. Below  sample code has bookTitle and btnSubmit in both the forms; the separate view models is bound using DOM-Element id that aggregates both the control sets.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
<div style="width: 600px; overflow: hidden;">
    <div style="width: 300px; float: left;" id="Form1">
        Book Title:
        <input data-bind="value: bookTitle" /><br />
        Book Price:
        <input data-bind="value: bookPrice" /><br />
        <button data-bind="click: btnSubmit">Submit</button>
    </div>
    <div style="display: table-cell;" id="Form2">
        Author Name:
        <input data-bind="value: authorName" /><br />
        Book Title:
        <input data-bind="value: bookTitle" /><br />
        <button data-bind="click: btnSubmit">Submit</button>
    </div>
</div>
<script src="./knockout-2.2.0.js"></script>
<script type="text/javascript">
    var viewModel_1 = {
        bookTitle: ko.observable("ASP.NET For Everyone"),
        bookPrice: ko.observable("$34.00"),
        btnSubmit: function () { alert(this.bookTitle() + ": " + this.bookPrice()); }
    };
    var viewModel_2 = {
        authorName: ko.observable("Dr. Someone"),
        bookTitle: ko.observable("ASP.NET For Everyone"),
        btnSubmit: function () { alert(this.authorName() + ": " + this.bookTitle()); }
    };
    ko.applyBindings(viewModel_1, document.getElementById("Form1"));
    ko.applyBindings(viewModel_2, document.getElementById("Form2"));
</script>