jon*_*aag 5 javascript backbone.js underscore.js
我可以将我的模板放在单独的.html文件中,并在index.html中引用它们吗?
index.html:
<script type="text/template" id="item-list" src="item-list-tmpl.html"></script>
Run Code Online (Sandbox Code Playgroud)
item-list-tmpl.html:
<div><%= ItemDescription %><%= ItemCode %></div>
Run Code Online (Sandbox Code Playgroud)
我试过了,但问题是它没有在index.html上显示模板,但它加载到适当的位置(使用firebug查看)
找到了可能的解决方案,但不建议用于生产环境.
来自http://coenraets.org/blog/2012/01/backbone-js-lessons-learned-and-improved-sample-app/#comment-35324
为此创建一个单独的js文件,并在js文件之前为模型,集合和视图调用它.
tpl = {
// Hash of preloaded templates for the app
templates:{},
// Recursively pre-load all the templates for the app.
// This implementation should be changed in a production environment. All the template files should be
// concatenated in a single file.
loadTemplates:function (names, callback) {
var that = this;
var loadTemplate = function (index) {
var name = names[index];
//console.log('Loading template: ' + name);
$.get('templates/' + name + '.html', function (data) {
that.templates[name] = data;
index++;
if (index < names.length) {
loadTemplate(index);
} else {
callback();
}
});
}
loadTemplate(0);
},
// Get template by name from hash of preloaded templates
get:function (name) {
return this.templates[name];
}
};
Run Code Online (Sandbox Code Playgroud)
之后将其添加到您的路由器
tpl.loadTemplates(['filename-of-your-external-html-file'], function () {
app = new AppRouter();
Backbone.history.start();
});
Run Code Online (Sandbox Code Playgroud)
应该这样做.但是再次不建议用于生产环境,因为将有数百个请求并可能削弱您的应用程序.