【发布时间】:2015-10-08 10:27:00
【问题描述】:
我正在尝试在加载所有模板时触发一个函数。这是通过每个模板的 loadTemplate 函数完成的。
我的问题是如何监听所有 .then() 完成,然后才触发我的 foo() 函数。
我尝试过使用 when() 和 promise,但是我没有成功地将它们绑定到外部,而我已经设法将它绑定到 loadTemplate(这不是我想要的为)。
我总是可以将每个 loadTemplate 绑定到一个计数器,并在每次迭代时检查计数器是否已达到每个模板的数量,但我确信有一种更优雅的方法可以做到这一点。
这是循环代码:
$.each(templates.hbs, function(idx, template) {
loadTemplate(template.name)
.then(function(templateStr){
var compiledTemplate = Handlebars.compile(templateStr);
if(template.isPartial){
Handlebars.registerPartial(template.key, compiledTemplate);
}
templates[template.key] = compiledTemplate;
});
});
以及触发后的函数:
function templateDone(){
console.log("done!");
}
感谢您的帮助!
编辑:也包括 loadTemplate 代码:
function loadTemplate (template) {
return new Promise(function (resolve, reject) {
$.ajax({
url: config.wwwroot + '/folder/' + template + '.hbs',
async: false,
success: function (result) {
resolve(result);
},
error: reject
});
});
}
【问题讨论】:
-
但我确信有更优雅的方法可以做到这一点我不太确定。
标签: javascript jquery ajax