jquery - loading handlebars template asynchronously -


i'm trying write function give me compiled handlebars template (i have templates in separate files) using ajax call template , compile use, need use promise can use it.

function gettemplate(name){     $.get('/'+name+'.hbs').success(function(src){        var template = handlebars.compile(src);        //can't return template here.     }); } 

how do promises can like:

$("a").click(function(e){     gettemplate('form').done(function(template){        $("body").append(template({                name: "my name"            })        );     }); }); 

chovy, see have accepted answer might interested know gettemplate can, chaining .then() rather .success(), written in question :

function gettemplate(name) {     return $.get('/'+name+'.hbs').then(function(src) {        return handlebars.compile(src);     }); } 

or, adopting charlietfl's idea pass in data , return promise of composed fragment :

function gettemplate(name, data) {     return $.get('/'+name+'.hbs').then(function(src) {        return handlebars.compile(src)(data);     }); } 

the nett effect identical charlietfl's version of gettemplate .then() makes unnecessary create deferred explicitly. code more compact.


Comments

Popular posts from this blog

c# - Send Image in Json : 400 Bad request -

jquery - Fancybox - apply a function to several elements -

An easy way to program an Android keyboard layout app -