我正在使用 Code School Backbone 教程中的代码,而我从他们的示例中使用的一些我已经为自己的目的而改编的代码似乎不起作用。基本上,我添加了一个侦听器来将新模型添加到集合中,效果很好,但是当我添加删除侦听器时,它似乎删除了我的所有视图。我认为这个问题与我认为的“el:'.monster'”有关,但我还没有找到正确的组合来解决它。
这是代码:
// MODEL
var Monster = Backbone.Model.extend({
defaults: {
name: '',
health: '',
defense: '',
attack: '',
damage: ''
}
});
// COLLECTION
var MonsterList = Backbone.Collection.extend({
model: Monster,
url: '/monsters',
initialize: function() {
this.on('remove', this.hideModel);
},
hideModel: function(model) {
model.trigger('hide');
}
});
var monsterList = new MonsterList();
var monsters = [
{name: 'Gobby', health: 10, defense: 10, attack: 5, damage: 4},
{name: 'Clobber', health: 15, defense: 10, attack: 7, damage: 4},
{name: 'Gumms', health: 9, defense: 10, attack: 5, damage: 2}
];
monsterList.reset(monsters);
// VIEW
var MonsterView = Backbone.View.extend({
el: '.monster',
template: _.template('<table>' +
'<th><%= name %></th>' +
'<tr><td>Health</td> <td><%= health %></td>' +
'<td>Defense</td><td><%= defense %></td></tr>' +
'<tr><td>Attack</td><td><%= attack %></td>' +
'<td>Damage</td><td><%= damage %></td><tr>' +
'</table>'
),
initialize: function() {
this.model.on('hide', this.remove, this);
},
remove: function() {
this.$el.remove();
},
render: function(){
this.$el.append(this.template(this.model.toJSON()));
}
});
var MonsterListView = Backbone.View.extend({
initialize: function() {
this.collection.on('add', this.addOne, this);
this.collection.on('reset', this.addAll, this);
},
addOne: function(monster) {
var monsterView = new MonsterView({model: monster});
this.$el.append(monsterView.render());
},
addAll: function() {
this.collection.forEach(this.addOne, this);
},
render: function() {
this.addAll();
}
});
var monsterListView = new MonsterListView({collection: monsterList});
monsterListView.render();
html 文件只是一个带有“monster”类的空 div。任何能帮助我朝着正确方向前进的事情都将不胜感激!