gpt4 book ai didi

knockout.js - applyBindings 的第二个参数是干什么用的?

转载 作者:行者123 更新时间:2023-12-03 08:37:16 25 4
gpt4 key购买 nike

我一直在寻找但找不到 applyBindings() 的文档.第二个参数可以合法包含什么?它可以是一个元素数组吗?它必须是单个元素吗?是否可以通过两次调用 applyBindings 将绑定(bind)应用于两个单独节点的子元素?

       ko.applyBindings(myViewModel, div1);
ko.applyBindings(myViewModel, div2);

最佳答案

KnockoutJS 是开源的。来自 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);
};
所以是的,它似乎必须是一个 DOM 节点。更具体地说, nodeType is 必须是 1 ( ELEMENT_NODE ) 或 8 ( COMMENT_NODE ),否则会引发错误。
relevant documentation ("Activating Knockout")不太明确地说它必须是一个 DOM 节点,但是(请参阅我添加的重点)确实说了同样的话:

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.


只要节点不共享树的一部分(例如,它们是 sibling ),您就可以在每个节点上安全地调用 applyBindings(事实上,这是使用第二个参数的一个原因)。
this related question对于一个典型的用例。

关于knockout.js - applyBindings 的第二个参数是干什么用的?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18990244/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com