Knockout Components ,模板已经注入到这个元素中,但还没有绑定

Knockout Components , the template has already been injected into this element, but isn't yet bound

来自Knockoutjs Docs这句话我没看懂:
模板已注入到此元素中,但尚未绑定。

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

new MyViewModel(params);

MyViewModel 是所需的视图模型实例。这是knockout中使用的工厂设计模式

如果您想在关联元素绑定到视图模型之前运行任何设置逻辑,或者使用任意逻辑来决定实例化哪个视图模型class:角色来了factory function .

将根据您在 运行 时间的逻辑选择视图模式。


the template has already been injected into this element, but isn't yet bound.

一旦您 return 您想要的视图模式,它就会绑定到您的 ko.components

所以假设 "my-component" 的模板是(不管它是如何定义的)

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

句子 "the template has already been injected into this element, but isn't yet bound" 描述了给定组件 DOM 的状态。 (A.K.A。componentInfo.elementcreateViewModel 函数的上下文中)

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

模板注入组件前:

<my-component></my-component>

模板注入组件后,绑定发生前:(这是调用createViewModel时DOM的状态,因此评论)

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

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

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

跨度在最后一步中只有文本,因为现在已应用绑定,并且 text 绑定已将文本添加到组件。


该注释表示 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