applyBindings 的第二个参数有什么用? [英] What's the applyBindings' second parameter used for?

查看:30
本文介绍了applyBindings 的第二个参数有什么用?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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);

推荐答案

KnockoutJS 是开源的.来自相关文件:

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);
};

所以是的,它似乎必须是单个 DOM 节点.更具体地说,nodeType 必须是1 (ELEMENT_NODE) 或 8 (COMMENT_NODE),否则会抛出错误.

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.

相关文档(Activating Knockout") 不太明确它必须是一个 DOM 节点,但是(请参阅我添加的强调)确实是在说同样的事情:

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:

或者,您可以传递第二个参数来定义要搜索data-bind 属性的文档的哪个部分.例如,ko.applyBindings(myViewModel, document.getElementById('someElementId')).这将激活限制为 ID 为 someElementId 的元素及其后代,如果您想拥有多个视图模型并将每个视图模型与页面的不同区域相关联,这将非常有用.

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.

只要节点不共享树的一部分(例如它们是兄弟节点),您就可以在每个节点上安全地调用 applyBindings(实际上,这是使用第二个参数的一个原因).

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.

这篇关于applyBindings 的第二个参数有什么用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆