I wonder how to work with sync data and handlebar helpers. I want to load cms messages to a single page application and I tried out following method and could not able to achieve it.
Please see following code.
function loadCmsMessage(key) {
var cms = {
"msg.001": "Hello {0} {1}"
};
var deferred = $.Deferred();
setTimeout(function () {
var msg = cms[key];
deferred.resolve(msg);
}, 1000);
return deferred.promise();
}
Handlebars.registerHelper('cms', function (key, arr) {
var promise = loadCmsMessage(key);
promise.done(function (str) {
str = Handlebars.Utils.escapeExpression(str);
if ($.isArray(arr)) {
$.each(arr, function (i) {
var safeStr = Handlebars.Utils.escapeExpression(arr[i]);
str = str.replace("{" + i + "}", safeStr);
});
}
var result = '<span class="cms-data">' + str + '</span>';
return new Handlebars.SafeString(result);
});
});
$(document).ready(function () {
var template = Handlebars.compile($("#myTemplate").html());
$("#wrap").html(template({
"person": ['Jane', 'Fonda']
}));
});
You can't. The return
statement is at the inner function of the Promise. Handlebars helpers don't allow asynchronousness.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.