javascript - Knockout Components ,模板已经注入(inject)到该元素中,但尚未绑定(bind)

标签 javascript knockout.js knockout-3.0 knockout-components

来自Knockoutjs Docs我不明白这句话:
模板已注入(inject)此元素,但尚未绑定(bind)。

ko.components.register('my-component', {
viewModel: {
    createViewModel: function(params, componentInfo) {
        // - 'params' is an object whose key/value pairs are the parameters
        //   passed from the component binding or custom element
        // - 'componentInfo.element' is the element the component is being
        //   injected into. When createViewModel is called, the template has
        //   already been injected into this element, but isn't yet bound.

        // Return the desired view model instance, e.g.:
        return new MyViewModel(params);
    }
},
template: ...
});

最佳答案

假设“my-component”的模板是(无论它是如何定义的)

<span class="foo" data-bind="text: 'foo'"></span>
<小时/>

句子“模板已被注入(inject)此元素,但尚未绑定(bind)”描述了给定组件的 DOM 状态。 (在 createViewModel 函数的上下文中又称为 componentInfo.element)

通过绑定(bind)组件的过程,组件的 DOM 如下所示:

在将模板注入(inject)组件之前:

<my-component></my-component>

将模板注入(inject)到组件中之后,但在绑定(bind)发生之前:(这是调用 createViewModel 时 DOM 的状态,因此有注释)

<my-component>
    <span class="foo" data-bind="text: 'foo'">
    </span>
</my-component>

绑定(bind)发生后:(这只能在 creteViewModel 返回 ViewModel 之后发生)

<my-component>
    <span class="foo" data-bind="text: 'foo'">
         foo
    </span>
</my-component>

跨度在最后一步中仅包含文本,因为现已应用绑定(bind),并且 text 绑定(bind)已将文本添加到组件。

<小时/>

该注释旨在表明 DOM 处于第二状态,这意味着如果您愿意,您可以通过 createViewModel 函数操作组件的 DOM 元素,尽管 KO 文档建议反对它:

Note that, typically, it’s best to perform direct DOM manipulation only through custom bindings rather than acting on componentInfo.element from inside createViewModel

关于javascript - Knockout Components ,模板已经注入(inject)到该元素中,但尚未绑定(bind),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27729730/

相关文章:

javascript - 在字符串中添加数字

javascript - jQuery attr() 无法设置属性

javascript - 使用 JAVAScript 从 Phonegap 应用程序向 DJANGO 提交表单

javascript - 为什么knockout-secure-binding会遇到这个语法错误

javascript - Angular .js :12759 : OPTIONS 405 (Method Not Allowed)

asp.net-mvc - 使用 Jquery UI Datepicker knockout Js - "Missing instance data for this datepicker"

mvvm - 是否有可能在 Knockout 中使用参数计算可观察值

javascript - Knockout JS removeAll() 第二次调用失败

javascript - 如何以编程方式加载 KnockoutJS 组件

css - 如何使 Knockout 成为 Knockout 可见标签使用 display :none ! 重要