I'm playing around with code from the Code School Backbone tutorial, and some of the code that I'm using from their examples that I've adapted for my own purposes doesn't seem to work. Basically, I've added a listener to add a new model to a collection, which works fine, but when I added the remove listener, it seems to delete all of my view. I think that the problem is related to the "el: '.monster'" in my view, but I haven't figure out the right mix to fix it.
Here is the code:
// 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();
The html file is just an empty div with the class 'monster'. Anything to help steer me in the right direction would be greatly appreciated!