正如 dandavis 所评论的,使用 Handlebars 你不能模板化对象,只能模板化字符串。但是,您可以使用 MutationObserver 将元素添加到 DOM 后获取它们。我创建了一些助手来执行此操作,请参阅jq
帮手渲染后栏 https://github.com/ekuusela/post-render-bars。也可以看看这个答案 https://stackoverflow.com/a/9145781/1630906针对不同方法的类似问题。
这是一个demo http://ekuusela.github.io/post-render-bars/example/withjquery.html#对于渲染后栏,请检查“在模板中定义 jQuery 元素”标题下的示例。
助手使用变异观察者 https://developer.mozilla.org/en-US/docs/Web/API/MutationObserver,这里是浏览器支持 http://caniuse.com/#feat=mutationobserver信息,请参阅精简版网络组件 http://webcomponents.org/polyfills/如果需要的话,可以使用polyfill。
相关代码简单说明:
watch.js https://github.com/ekuusela/post-render-bars/blob/master/watch.js定义一个函数forHtml(html, callback)
当 DOM 中遇到给定的 html 时,它会触发回调。它修改 html 以暂时拥有一个使其独一无二的类。
jQueryHelpers.js https://github.com/ekuusela/post-render-bars/blob/master/jQueryHelpers.js定义助手jq
。助手使用watch.forHtml
函数来监视由助手定义的块,并使用 jquery 元素作为参数调用您传递到模板的函数。
这是我链接的示例模板的简化版本:
<p>button with a handler: {{#jq setHandler}}<button>try me</button>{{/jq}}</p>
And js:
var context = {
setHandler: function(element) {
element.on('click', function() {
alert('clicked');
});
}
};
var html = template(context);
// append html somewhere and the setHandler will be invoked