What's the applyBindings' second parameter used for?
KnockoutJS is open source. From the relevant file:
ko.applyBindings = function (viewModelOrBindingContext, rootNode) {
// Some code omitted for brevity...
if (rootNode && (rootNode.nodeType !== 1) && (rootNode.nodeType !== 8))
throw new Error("ko.applyBindings: first parameter should be your view model; second parameter should be a DOM node");
rootNode = rootNode || window.document.body; // Make "rootNode" parameter optional
applyBindingsToNodeAndDescendantsInternal(getBindingContext(viewModelOrBindingContext), rootNode, true);
};
So yes, it seems it must be a single DOM node. To be more specific, the nodeType is must be either 1 (ELEMENT_NODE
) or 8 (COMMENT_NODE
), otherwise an Error is thrown.
The relevant documentation ("Activating Knockout") is less explicit that it must be a DOM node, but (see emphasis, added by me) does kind of say the same thing:
Optionally, you can pass a second parameter to define which part of the document you want to search for
data-bind
attributes. For example,ko.applyBindings(myViewModel, document.getElementById('someElementId'))
. This restricts the activation to the element with IDsomeElementId
and its descendants, which is useful if you want to have multiple view models and associate each with a different region of the page.
As long as nodes don't share part of the tree (e.g. they're siblings) you can call applyBindings safely on each of the nodes (in fact, that's one reason to use the second argument).
See this related question for a typical use case.
Can be found at the following link... http://knockoutjs.com/documentation/observables.html
In case you’re wondering what the parameters to ko.applyBindings do,
The first parameter says what view model object you want to use with the declarative bindings it activates
Optionally, you can pass a second parameter to define which part of the document you want to search for data-bind attributes. For example, ko.applyBindings(myViewModel, document.getElementById('someElementId')). This restricts the activation to the element with ID someElementId and its descendants, which is useful if you want to have multiple view models and associate each with a different region of the page.
In case anyone is looking to use classes for implementing this
for i of $('.myView')
ko.applyBindings(new MyView(),$('.myView')[i])