cho*_*ovy 7 jquery promise handlebars.js
我正在尝试编写一个函数,它将为我提供一个编译的把手模板(我将所有模板放在不同的文件中),使用ajax调用来获取模板并编译它以供使用,但我需要使用一个承诺,所以我可以实际上使用它.
function getTemplate(name){
$.get('/'+name+'.hbs').success(function(src){
var template = Handlebars.compile(src);
//can't return the template here.
});
}
Run Code Online (Sandbox Code Playgroud)
我如何用promises做到这一点,所以我可以这样做:
$("a").click(function(e){
getTemplate('form').done(function(template){
$("body").append(template({
name: "My Name"
})
);
});
});
Run Code Online (Sandbox Code Playgroud)
Bee*_*oot 16
Chovy,我看到你已经接受了一个答案,但你可能有兴趣知道getTemplate可以通过链接.then()而不是.success()像问题一样写出来:
function getTemplate(name) {
return $.get('/'+name+'.hbs').then(function(src) {
return Handlebars.compile(src);
});
}
Run Code Online (Sandbox Code Playgroud)
或者,采用charlietfl的想法传递数据并返回完全组合片段的Promise:
function getTemplate(name, data) {
return $.get('/'+name+'.hbs').then(function(src) {
return Handlebars.compile(src)(data);
});
}
Run Code Online (Sandbox Code Playgroud)
nett效果与charlietfl的版本相同,getTemplate但是.then()没有必要明确地创建Deferred.因此代码更紧凑.
| 归档时间: |
|
| 查看次数: |
8168 次 |
| 最近记录: |