jQuery淘汰赛:在内存中渲染模板 [英] Jquery knockout: Render template in-memory

查看:98
本文介绍了jQuery淘汰赛:在内存中渲染模板的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个淘汰赛模板:

<script id="draggableHelper" type="text/x-jquery-tmpl">
    <div class="draggableHelper">
        <span data-bind="text: Name"></span>
    </div>
</script>

是否可以通过发送对象以填充模板来生成模板的结果并将其保存到内存中?

Is possible to generate the result of the template, and save it into memory, by sending the object to populate the template?

类似的东西:

var result = ko.renderTemplate($("#draggableHelper").html(), { Name: "Test" });

推荐答案

是的,可以将绑定应用于未附加到DOM的节点.只需使用非常有用的功能ko.applyBindingsToNode即可获得所需的结果.

Yes it's possible to apply bindings to nodes unattached to the DOM. Just use very useful function ko.applyBindingsToNode to achieve the desired result.

ko.renderTemplateX = function(name, data){
    // create temporary container for rendered html
    var temp = $("<div>");
    // apply "template" binding to div with specified data
    ko.applyBindingsToNode(temp[0], { template: { name: name, data: data } });
    // save inner html of temporary div
    var html = temp.html();
    // cleanup temporary node and return the result
    temp.remove();
    return html;
};

看看这个小例子: http://jsfiddle.net/6s4gq/

更新:

最初是ko.renderTemplate方法,但Knockout中有内置方法 同名.覆盖ko.renderTemplate可能会使您的应用程序停止工作,尤其是在使用template绑定的情况下.小心!

Originally it was ko.renderTemplate method but there is built-in method in Knockout with the same name. Overriding ko.renderTemplate could stop working your application, especially if you're using template binding. Be careful!

这篇关于jQuery淘汰赛:在内存中渲染模板的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆