Passing options to templates in knockout 1.3

為{幸葍}努か 提交于 2019-12-12 08:54:36

问题


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>

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>

But the new native template engine doesn't respect templateOptions.

Is there some other way I can pass arbitrary data into a template?


回答1:


As you discovered, the native template engine does not support templateOptions which was a wrapper to the jQuery Template plug-in's options functionality.

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/

Note that in a foreach scenario, you would find your options on $parent.$item rather than just $item.




回答2:


I would suggest Sanderson's proposal where you would pass new literal to template data that contains model and extra data (template options).

data-bind="template: { name: 'myTemplate', data: { model: $data, someOption: someValue } }"

Working Demo http://jsfiddle.net/b9WWF/

Source https://github.com/knockout/knockout/issues/246#issuecomment-3775317



来源:https://stackoverflow.com/questions/8068305/passing-options-to-templates-in-knockout-1-3

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!