【发布时间】:2015-08-19 16:58:51
【问题描述】:
类似于this question,我正在寻找一种通过 Javascript 承诺加载模板的方法。我遇到的问题是将编译后的模板返回到主干视图。注意:this.getFile() 返回一个new Promise,它会按预期获取模板。
template: function(attributes) {
this.getFile('/path/to/template').then(function(tpl) {
var compiled = Handlebars.compile(tpl);
return compiled(attributes);
}, function(error) {
console.error('Failed!', error);
});
}
在视图的initialize 中,我有一个监听器设置为
initialize: function() {
this.model.on('change', this.render, this);
}
从服务器获取数据时按预期触发。
问题出在render函数执行的时候
render: function() {
...
this.$el.html(this.template(attributes));
...
}
没有任何东西像我期望的那样呈现给 html。我确定我在模板承诺回调中遗漏了一些简单的东西,但是无论我更改什么,html 都不会呈现,也不会出现错误。
【问题讨论】:
-
另一个问题的答案有什么问题?你只需要修改你的代码,让
template得到一个回调函数(或返回一个promise)而不是试图返回一个值。 -
@muistooshort 另一个问题是关于他们如何返回模板并将其应用于渲染方法的模糊,这就是我的问题。除了
Promise之外,manager是什么?tpl如何从Handlebars.compile传递到回调中?在这一点上,我对 js promises 的经验和知识是有限的。 -
您不会从您的
template函数中返回任何内容,而是给它一个函数,以便在 AJAX 调用完成时调用它:this.template('template_name', function(tmpl) { /* do things with tmpl here */ })。 -
@muistooshort 使用您的 cmets 帮助解决了这个问题。谢谢!
标签: javascript templates backbone.js handlebars.js