淘汰带有命名模板的3.2组件

Knockout 3.2 components with named templates?

本文关键字:2组件 淘汰      更新时间:2023-09-26

我正在尝试使用knockout 3.2.0中的新组件系统。

目前没有太多的文档,但这是可行的。

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

但是template绑定允许您指定一个已经存在于DOM中的模板名称,例如:

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

那么你可以这样做:

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

所以我试了这个:

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

但它不起作用。是否有办法在新组件中使用命名模板,或者它们必须内联或加载AMD。

感谢

编辑:在RP Niemeyer的回答之后,为了澄清,这里是我尝试他的答案的模板:

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

组件代码:

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

加载模板,但将其视为转义字符串。

想法?

您可以传递一个element属性,该属性可以是元素本身,也可以是元素的id字符串,例如:

template: { element: 'myTmpl' }

在v3.2.0 beta中,这种情况没有得到很好的处理,因此需要InternalFX

将在v3.2.0 final中修复。它将如您所期望的那样工作-只需引用scripttemplatetextarea元素,其逻辑内容将被解释为模板节点。

如果您感兴趣,修复和测试这个的提交在这里:https://github.com/knockout/knockout/pull/1454

最后用一些hack解决了这个问题…我希望这个问题能得到优秀开发者的更好回答。

这工作。基本上,我只是手动加载模板文本并将其传递给register函数。所以它就像内联一样工作。

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