我正在尝试将模板传递给我的视图。我有几个不同的模板我想要使用,并希望能够在我的路由器中切换它们。我没有错误,但我没有得到任何结果。看起来我的第二个视图中没有调用initialize
方法。这是我的代码:
(function() {
window.App = {
Models: {},
Collections: {},
Views: {},
Router: {}
};
window.template = function(id) {
return _.template( $('#' + id).html() );
};
var vent = _.extend({}, Backbone.Events);
_.templateSettings.interpolate = /\[\[(.+?)\]\]/g;
App.Router = Backbone.Router.extend({
routes: {
'' : 'index',
'send-message' : 'sendMessage',
'*other' : 'other'
},
index: function() {
t = new (App.Collections.Tables.extend({ url: 'main-contact'}))();
tables = new (App.Views.Tables.extend({
collection: t, template: template('mainContactTemplate')}))();
$('#web-leads').html(tables.el);
},
sendMessage: function() {
t = new (App.Collections.Tables.extend({ url: 'send-message'}))();
tables = new App.Views.Tables.extend({
collection: t, template: template('sendMessageTemplate')});
$('#web-leads').html(tables.el);
},
other: function() {
}
});
// Main Contact
App.Models.Table = Backbone.Model.extend({});
App.Collections.Tables = Backbone.Collection.extend({
model: App.Models.Table,
initialize: function(models, options) {
this.fetch({
success: function(data) {
//console.log(data.models);
}
});
if (options) {
this.url = this.url || options.url;
}
}
});
App.Views.Tables = Backbone.View.extend({
tagName: 'ul',
initialize: function() {
this.collection.on('reset', this.render, this);
},
render: function() {
return this.collection.each(this.addOne, this);
},
addOne: function(model) {
var t = new App.Views.Table({ model: model, template: template});
this.$el.append(t.render().el);
return this;
}
});
App.Views.Table = Backbone.View.extend({
tagName: 'li',
template: this.template,
initialize: function (attrs) {
this.options = attrs;
console.log(this.options);
},
render: function() {
this.$el.html(this.template(this.model.toJSON()));
return this;
}
});
new App.Router();
Backbone.history.start();
})();
编辑:我错过了一些括号。但现在我得到一个无法识别的表达式的错误。现在正在调用Initialize。
答案 0 :(得分:3)
在App.Views.Table
中进行此操作的方式是(据我所知)使用Backbone模板的“标准”方式。当然,有几种选择,但每种说法都没有“错误”。
话虽如此,您的代码中确实存在一些问题。让我们从:
开始template: this.template,
在代码运行时,您不在App.Views.Tables
的实例中,您在全局空间中声明了一个类(稍后)将用于创建实例。但就在那时,this
只是指window
。您真正想要做的是在initialize
中设置模板,这会导致我:
initialize: function(options) {
this.template = options.template;
},
但接下来还有最后一个问题:
var t = new App.Views.Table({ model: model, template: template});
该函数中没有模板变量,所以你真的在做template: undefined
。那应该使用真实的模板。
所有这一切,您可能只想考虑将模板直接放在视图上,就像您尝试的那样:
template: Handlebars.compile('<span>{{test}}</span>'),
毕竟,任何给定的视图都应该始终使用相同的模板,对吧?此外,您可能需要考虑移动:
render: function() {
this.$el.html(this.template(this.model.toJSON()));
return this;
}
到父类,以便您可以在所有模板化视图之间共享它,而不必重复它。