在我的代码中,我尝试从缓存中加载模板。如果模板不在缓存中 - 通过ajax从服务器加载模板。加载完成后,我想将模板缓存并返回。这里是:如何从缓存或ajax加载模板返回模板?
var manager = function() {
return {
cache: [],
getTemplate: function (templateId) {
this.templateId = templateId;
if (this.cache[this.templateId]) {
return this.cache[this.templateId];
}
return this.loadTemplate();
},
loadTemplate: function() {
var
self = this;
$.get('/assets/templates/' + this.templateId + '.html', function (templateHtml) {
self.cache[self.templateId] = templateHtml;
return self.getTemplate(self.templateId);
});
}
}
}
var
manager = manager();
$('body').append(manager.getTemplate('template'));
我知道我的代码不工作,因为在函数loadTemplate结束后ajax请求完成。我认为代码可以用延迟对象修复,但不知道如何。任何人都可以帮助我找到解决方案吗?
非常感谢,这是我需要的! – Evgeniy