There are several directions that you can go for something like this:
you can apply different view models to different elements, as you mentioned like:
var viewModelOne = { ... };
var viewModelTwo = { ... };
ko.applyBindings(viewModelOne, containerElementOne);
ko.applyBindings(viewModelOne, containerElementOne);
You can even dynamically apply a binding with its data to an element like:
var viewModelOne = { ... };
ko.applyBindingsToNode(containerElement, { template: { name: 'itemTemplate', foreach: items }, viewModelOne);
Would be like this sample: http://jsfiddle.net/rniemeyer/gYk6f/
You can also do something like:
var mainViewModel = {
sideBarModel = ko.observable(),
contentModel = ko.observable()
};
Then, bind it like:
<div data-bind="with: contentModel"></div>
<div data-bind="with: sideBarModel"></div>
They, can even be nested like:
<div data-bind="with: contentModel">
...
<div data-bind="with: $root.sideBarModel"></div>
</div>
Since, the models are observable, they can initially be empty and get populated on demand.
You can certainly use named templates in those cases as well like:
<div data-bind="template: { name: "contentTmpl", data: contentModel }"></div>
<div data-bind="template: { name: "sideBarTmpl", data: sideBarModel }"></div>
For the Extra Credit question:
p
tags cannot contain other block level elements (like your div
). The browser moves it out of the p
tag. Replace your div
with a span
and it will behave like you are expecting (or replace p
with div
).
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…