Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
864 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);
question from:https://stackoverflow.com/questions/18990244/whats-the-applybindings-second-parameter-used-for

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

1 Answer

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...