来自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/