Chapter 6. Multiple ViewModels, Custom Data Bindings, and Templates

Binding Multiple ViewModels

Whether you are simply looking to keep your ViewModels nice and clean, or you have a shared ViewModel that appears on each page, there will come a time when you wish to bind multiple ViewModels on a single page.

Knockout makes this quite easy. There is an optional second parameter that can be passed into the ko.applyBindings function that tells Knockout to limit its binding within this block of HTML.

Example 6-1 almost looks the same as some of the previous examples where a simple name was being bound. There are a few subtle differences that get this to work.

Example 6-1. Binding two ViewModels on a single page
<!DOCTYPE html>
    <title>Data Binding with KnockoutJS</title>

    <div id="viewModel1"> 
        <h1 data-bind="text: name"></h1> 

    <div id="viewModel2"> 
        <h1 data-bind="text: name"></h1> 

    <script type='text/javascript' src='js/knockout-3.2.0.js'></script> 
        function ViewModel(name) { 
            var self = this; 

   = name; 

        var viewModel1 = new ViewModel('Steve Kennedy'); 
        ko.applyBindings(viewModel1, document.getElementById('viewModel1')); 

        var viewModel2 = new ViewModel('Mike Wilson'); 
        ko.applyBindings(viewModel2, document.getElementById('viewModel2')); 

First, there are two h1 tags placed inside their own div tag. This div tag contains an id attribute that is important for this example to function properly.

In the JavaScript, ...

Get Knockout.js now with O’Reilly online learning.

O’Reilly members experience live online training, plus books, videos, and digital content from 200+ publishers.