knockout.js - 如何使用带有 knockout 、 knockout 映射和 jsrender 的模板

标签 knockout.js knockout-mapping-plugin jsrender

我想使用 jsRender 模板来渲染 fullName,即 firstName + ' ' + lastName。它不渲染带有数据的模板,而是渲染为 {{=firstName}} {{=lastName}}。我怎样才能做到这一点?

实例:http://jsbin.com/inijay/2/edit

JS:

var data = { "firstName": "Ian", "lastName": "Davis" };
var viewModel = ko.mapping.fromJS(data);
ko.applyBindings(viewModel);

HTML:

<input data-bind="value: firstName" type="text" />
<input data-bind="value: lastName" type="text" />
<span data-bind="template: 'fullNameTemplate'"></span>

模板:

<script id="fullNameTemplate" type="text/x-jquery-tmpl">
  {{=firstName}} {{=lastName}}
</script>

输出如下:broken jsrender template output

最佳答案

您必须安装自己的templateEngine。这是最终的结果:http://jsbin.com/inijay/3/edit

相关代码如下:

ko.jsrenderTemplateEngine = function () { };
ko.jsrenderTemplateEngine.prototype = ko.utils.extend(new ko.templateEngine(), {
    renderTemplateSource: function (templateSource, bindingContext, options) {
        // Precompile the wrapping div for templating
        var precompiled = templateSource['data']('precompiled');
        if (!precompiled) {
            precompiled = $('<div>', { text: templateSource.text() });
            templateSource['data']('precompiled', precompiled);
        }
        // Unwrap observables
        var unwrapped = ko.mapping.toJS(bindingContext.$data);
        // Render and parseHTMLFragment
        return ko.utils.parseHtmlFragment(precompiled.render(unwrapped));
    }
});
ko.setTemplateEngine(new ko.jsrenderTemplateEngine());

我还更改了您的 jsrender 模板:

<script id="fullNameTemplate" type="text/x-jquery-tmpl">
    {{:firstName}} {{:lastName}}
</script>

我从这里抄袭了基本的代码设计:http://knockoutjs.com/documentation/template-binding.html#note_6_using_the_underscorejs_template_engine

顺便说一句,这个解决方案似乎并没有那么快,因为 jsrender 的最佳性由于必须始终解开可观察对象而变得无用。我相信使用 Knockout 的原生模板会更好。

关于knockout.js - 如何使用带有 knockout 、 knockout 映射和 jsrender 的模板,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12716486/

相关文章:

javascript - 确定对象属性是否为 ko.observable

c# - 将 MVC 数据传递给 Knockout View 模型

jquery - 关于不同 jQuery 模板的建议

jquery - 将可排序索引值绑定(bind)到 knockout View 模块

javascript - 如何在 jsview if 语句中使用转换器?

javascript - JSRender 模板自定义标签使用

knockout.js - MVC4 中带有 ko 的示例网格

javascript - SELECT with 2 optgroups build with KnockOut 将值重置为空

javascript - Knockout.js 双向绑定(bind) : Number Formatted as String

javascript - Knockout.js 使每个嵌套对象成为 Observable