If you look at the function below, on line 11 where it alert(template);
. It prints undefined
. If I alert(template);
inside the ajax succes
ajax is asynchronous. to explain in simple terms: ajax works like it runs on a separate "thread", processing in the background while your code continues.
by the time you called load_template()
, it alerts after $.ajax()
was called but before the template was returned thus undefined
.
what you can do is this so everything runs after a success has been returned:
function load_template(path, data, callback){
$.ajax({
url: path,
success: function(uncompiled_template){
var template = Handlebars.compile(uncompiled_template);
alert(template);
if(callback){
callback(template, data);
}else{
return template(data);
}
}
});
}