我已经看到一些长篇大论的答案,关于如何加载模板以进行渲染,涉及到_underscore模板实用程序等。下面我得到了一些有用的东西:
$.ajax({
url: 'template.tmp',
type: 'get',
success: function(data) {
$('html').append(data);
}
});
代码位于jquery加载之后,但在使用模板的任何脚本之前。这样做可以吗?或者为什么不像这样加载模板是一个好主意?templates.tmp文件中包含模板
<script type="text/template" id="tmpId"></script>
标签。它们似乎几乎可以立即加载到DOM中。我已经准备好因为这个实现而受到批评,但我只想知道为什么。我唯一能想到的就是如果调用的是"error:“而不是"success:”,那么可能需要进行一些处理。谢谢。
发布于 2013-05-06 13:40:27
我决定开发我自己的基于OO的解决方案。这是构造函数:
var TemplateLoader = function(templatePath) {
this.template = templatePath;
this.loaded = false;
this.error = false;
}
下面是这些方法:
TemplateLoader.prototype.setReady = function (state) {
this.loaded = state;
}
TemplateLoader.prototype.setError = function (state) {
this.error = state;
}
TemplateLoader.prototype.isReady = function () {
return this.loaded;
}
TemplateLoader.prototype.isError = function () {
return this.error;
}
TemplateLoader.prototype.loadTemplate = function() {
templateLoader = this;
$.ajax({
url: this.template,
type: 'get',
success: function(data) {
$('html').append(data);
templateLoader.setReady(true);
},
error: function() {
templateLoader.setError(true);
}
});
}
下面是如何使用它:
templateLoader = new TemplateLoader('template.tmpl');
templateLoader.loadTemplate();
并检查模板是否已加载:
templateLoader.isReady() //true for loaded
templateLoader.isError() //true for error loading template, eg. template doesn't exist
再一次,我非常感谢任何人在这段代码中看到的任何问题的反馈。如何检查附加到HTML的DOM对象。值得吗?
https://stackoverflow.com/questions/16386150
复制