Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
640 views
in Technique[技术] by (71.8m points)

knockout.js - What's the applyBindings' second parameter used for?

I have been looking but cannot find the documentation for applyBindings(). What can the second parameter legally contain? Can it be an array of elements? Must it be a single element? Can the bindings be applied to the child elements of two separate nodes by calling applyBindings twice?

       ko.applyBindings(myViewModel, div1);
       ko.applyBindings(myViewModel, div2);
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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 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.

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...