Let’s suppose we have a DOM tree:
<div id="rootNode">
<span data-bind="..." >
</span>
<div>
<div>
<span data-bind="..."> </span>
</div>
<div id="subNode1" >
<span data-bind="..." > </span>
</div>
</div>
</div>
So we can bind model to that tree
ko.applyBindings(model, document.getElementById('rootNode'));
But what if we want bind subNode1 to other model? If just write
ko.applyBindings(model, document.getElementById('subNode1'));
It doesn’t work I guess because of first data binding overlap second.
And now why I want to do that. I have a lib with a few independent components which I implemented using Knockout. Components look like this:
function ComboBox(container)
{
this.name = new ko.observable();
this.someValue1 = new ko.observable();
this.someValue2 = new ko.observable();
ko.applyBindings(this, document.getElementById(container));
}
And unfortunately I can’t write:
SomeBigComponent('rootNode');
ComboBox('subNode');
How can I resolve that problem? And second question is it good to organize code in this way?
The typical way to handle this situation is to create a main view model that is a container for sub-view models.
So, you could have
Then, if you are using 1.3 beta, you would do something like:
Prior to 1.3, you would something like:
In either case, you would be able to call
ko.applyBindingsonce for the entire document.