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><divid="viewModel1"><h1data-bind="text: name"></h1></div><divid="viewModel2"><h1data-bind="text: name"></h1></div><scripttype='text/javascript'src='js/knockout-3.2.0.js'></script><script>functionViewModel(name){varself=this;self.name=name;};varviewModel1=newViewModel('Steve Kennedy');ko.applyBindings(viewModel1,document.getElementById('viewModel1'));varviewModel2=newViewModel('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, ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access