O'Reilly logo

Knockout.js by Jamie Munro

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

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>
<html>
<head> 
    <title>Data Binding with KnockoutJS</title>
</head>
<body> 

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

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

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

            self.name = 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')); 
    </script>
</body>
</html>

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, ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required