Search code examples
javascriptknockout.jsknockout-components

Knockout 3.2 components with named templates?


I'm trying to use the new components system in knockout 3.2.0.

There isn't much documentation at the moment, but this does work.

ko.components.register('price-input', {
  template: '<span>price-input</span>'
})

However the template binding allows you to specify a template name that already exists in the DOM, such as:

<script type="text/html" id="price_input">
  <span>price-input</span>
</script>

Then you could do this:

<div data-bind="template: {name: 'price_input'}"></div>

So I tried this:

ko.components.register('price-input', {
  template: {name: 'price_input'}
})

but it doesnt work. Is there a way to use named templates with the new components, or must they be inline or loaded with AMD.

Thanks

Edit: After RP Niemeyer's answer, for clarification here is the template I tried his answer with:

<script type="text/html" id="ifx_price_input">
  <h4>PRICE INPUT <span data-bind="text: value"></span></h4>
</script>

Here is the component code:

ko.components.register('price-input', {
  template: {element: 'ifx_price_input'}
})

It does load the template, but treats it as an escaped string.

Ideas?


Solution

  • In v3.2.0 beta, this case wasn't handled well, hence the hackery needed by InternalFX.

    This will be fixed in v3.2.0 final. It will work as you expect - simply reference a script, template, or textarea element, and its logical contents will be intepreted as template nodes.

    In case you're interested, the commit that fixes and tests this is here: https://github.com/knockout/knockout/pull/1454