From Knockoutjs Docs i don't understand this sentence :
the template has already been injected into this element, but isn't yet bound.
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: ...
});
So let's say the template for "my-component" is (regardless of how it's defined)
<span class="foo" data-bind="text: 'foo'"></span>
The sentence "the template has already been injected into this element, but isn't yet bound" describes the state of the DOM for a given component. (A.K.A. componentInfo.element
in the context of the createViewModel
function)
Through the process of binding the component, the DOM for the component looks like this:
Before the template has been injected into the component:
<my-component></my-component>
After the template has been injected into the component, but before binding happens: (this is the state of the DOM when createViewModel
is called, hence the comment)
<my-component>
<span class="foo" data-bind="text: 'foo'">
</span>
</my-component>
After binding happens: (this can only happen after creteViewModel
has returned the ViewModel)
<my-component>
<span class="foo" data-bind="text: 'foo'">
foo
</span>
</my-component>
The span only has text in the last step because bindings have now been applied, and the text
binding has added text to the component.
The comment is meant to indicate that the DOM is in the second state, which means you could manipulate the DOM elements of the Component from the createViewModel
function, if you wanted, though the KO documentation recommends against it:
Note that, typically, it’s best to perform direct DOM manipulation only through custom bindings rather than acting on componentInfo.element from inside createViewModel