If you look at the function below, on line 11 where it alert(template);. It prints undefined. If I alert(template); inside the ajax success callback, it prints no problem. Since template is defined at the top of the function, shouldn’t this be global through out the entire function? Can someone assist me with this?
function load_template(path, data, callback){
var template;
$.ajax({
url: path,
success: function(uncompiled_template){
template = Handlebars.compile(uncompiled_template);
}
});
alert(template);
if(callback){
callback(template, data);
}else{
return template(data);
}
}
No, it’s not a scope issue, it’s a timing issue.
The AJAX call is asynchronous, so the success callback runs later, when the response arrives. The variable is simply not set yet, when you try to use it.
You can’t return the value from the function, as the success callback never runs until you have exited the function. Always use the callback that is sent to the function: