问题描述
在knockoutjs 1.2.1我能做到:
In knockoutjs 1.2.1 I could do:
<div data-bind="template: {name: 'Bar', foreach: persons, templateOptions:{fooMode: true} }"/>
<script id='Bar'>
{{if $item.fooMode}} FOO! {{/if}}
</script>
我试图将其翻译为淘汰1.3.0beta
Which I have tried to translate to knockout 1.3.0beta as
<div data-bind="template: {name: 'Bar', foreach: persons, templateOptions:{fooMode: true} }"/>
<script id='Bar'>
<span data-bind="if: $item.fooMode">FOO!</span>
</script>
但新的原生模板引擎不尊重templateOptions。
But the new native template engine doesn't respect templateOptions.
还有其他方法可以将任意数据传递到模板中吗?
Is there some other way I can pass arbitrary data into a template?
推荐答案
正如您所发现的,本机模板引擎不支持 templateOptions
这是jQuery Template插件的选项
功能的包装。
As you discovered, the native template engine does not support templateOptions
which was a wrapper to the jQuery Template plug-in's options
functionality.
你可以采取两种方式:
将您的数据放在视图模型上并使用 $ root.fooMode
或 $ parent.fooMode
模板。这将是最简单的选项。
Two ways that you could go:Place your data on your view model and use $root.fooMode
or $parent.fooMode
inside of your template. This would be the easiest option.
否则,如果您不想在视图模型中使用该值,则可以使用自定义绑定来操作上下文,如:
Otherwise, if you don't want the value in your view model, then you can use a custom binding to manipulate the context like:
ko.bindingHandlers.templateWithOptions = {
init: ko.bindingHandlers.template.init,
update: function(element, valueAccessor, allBindingsAccessor, viewModel, context) {
var options = ko.utils.unwrapObservable(valueAccessor());
//if options were passed attach them to $data
if (options.templateOptions) {
context.$data.$item = ko.utils.unwrapObservable(options.templateOptions);
}
//call actual template binding
ko.bindingHandlers.template.update(element, valueAccessor, allBindingsAccessor, viewModel, context);
//clean up
delete context.$data.$item;
}
}
以下是使用中的示例:
Here is a sample in use: http://jsfiddle.net/rniemeyer/tFJuH/
请注意,在 foreach
方案中,您会在 $ parent。$ item
上找到您的选项,而不仅仅是 $ item
。
Note that in a foreach
scenario, you would find your options on $parent.$item
rather than just $item
.
这篇关于将选项传递给击倒1.3中的模板的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!