[英]backbone.js / underscore.js error: has no method 'html'
[英]external html template for underscore.js and backbone.js
我可以將我的模板放在單獨的.html文件中,並在index.html中引用它們嗎?
index.html:
<script type="text/template" id="item-list" src="item-list-tmpl.html"></script>
item-list-tmpl.html:
<div><%= ItemDescription %><%= ItemCode %></div>
我試過了,但問題是它沒有在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];
}
};
之后將其添加到您的路由器
tpl.loadTemplates(['filename-of-your-external-html-file'], function () {
app = new AppRouter();
Backbone.history.start();
});
應該這樣做。 但是再次不建議用於生產環境,因為將有數百個請求並可能削弱您的應用程序。
我使用jQuery和一個簡單的TemplateCache對象為此編寫了一個解決方案:
http://lostechies.com/derickbailey/2012/02/09/asynchronously-load-html-templates-for-backbone-views/
我最近更新了模板加載以使用名為TrafficCop的jQuery插件: http : //lostechies.com/derickbailey/2012/03/20/trafficcop-a-jquery-plugin-to-limit-ajax-requests-for-a -resource /
希望有所幫助。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.