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, ...
Get Knockout.js now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.