我的每个功能都有问题。我的控制台是错误:
window.App = {
Models: {},
Views: {},
Collections: {}
};
window.template = function (id) {
return _.template($('id' + id).html());
};
App.Models.Table = Backbone.Model.extend({
defaults: {
name: 'Table Name',
},
});
App.Collections.Tables = Backbone.Collection.extend({
model: App.Models.Table,
url: 'tables.json'
});
App.Views.Tables = Backbone.View.extend({
tagName: 'ul',
initialize: function() {
this.collection.fetch({reset:true});
this.collection.on('reset', this.render);
this.collection.on('add', this.addOne, this );
},
render: function () {
this.collection.each(this.addOne, this);
return this;
},
addOne: function(table) {
var table = new App.Views.Table({ model: table });
this.$el.append( table.render().el );
table.render();
}
});
App.Views.Table = Backbone.View.extend({
tagName: 'li',
initialize: function() {
this.model.on('destroy', this.remove, this)
},
render: function () {
this.$el.html( this.model.get('name') );
return this;
},
});
var tablesCollection = new App.Collections.Tables();
var tablesView = new App.Views.Tables({ collection: tablesCollection });
我无法找到错误。 我的json文件:
[
{"name": "Table 1","stts": "redstts","id": 1},
{"name": "Table 2","stts": "redstts","id": 2},
{"name": "Table 3","stts": "redstts","id": 3},
{"name": "Table 4","stts": "redstts","id": 4},
{"name": "Table 5","stts": "redstts","id": 5}
]
我想从集合中渲染我的所有对象,之后我想添加事件以在点击后添加下一个表格。但我的问题是为什么这不起作用?
答案 0 :(得分:4)
渲染没有正确的上下文。
this.collection.on('reset', this.render);
this.collection.on('add', this.addOne, this );
您需要添加上下文参数(第三个参数)。
this.collection.on('reset', this.render, this);