I have a UserCollection which is handled by a UsersView (list). Single elements, models, are handled as UserView.
When I now fetch a new UserCollection (other url) than the collection object itselfs updates (containes the new user models) but the html list remains.
ListView:
var ContactsView = Backbone.View.extend({
tagName: "ul",
className: "contacts unstyled",
events: {
},
initialize: function() {
this.collection = new UserCollection();
this.collection.bind('add', this.addContact, this);
this.collection.bind('remove', this.removeContact, this); // not getting called
this.collection.bind('reset', this.listContacts, this);
this.collection.fetch();
},
render: function() {
this.$el.html();
return this;
},
listContacts: function(contacts) {
contacts.each(function(contact) {
this.$el.append(new ContactView({ model: contact }).render().el);
}.bind(this));
},
addContact: function(contact) {
this.$el.append(new ContactView({ model: contact }).render().el);
},
// this is not getting executed
removeContact: function(contact) {
console.log(["removeContact fired"]);
contact.unset();
}
});
Item-View
var ContactView = Backbone.View.extend({
tagName: "li",
className: "contact",
template: _.template(ContactTemplate),
events: {
"mouseenter li.contact": "expandOptions"
, "mouseleave li.contact": "collapseOptions"
, "click": "removeContact"
},
initialize: function() {
this.model.bind('change', this.render, this);
this.model.bind('remove', this.remove, this);
this.model.bind('destroy', this.remove, this);
this.model.bind('unset', this.remove, this);
},
render: function() {
this.$el.html(this.template(this.model.toJSON()));
return this;
},
expandOptions: function() {
},
collapseOptions: function() {
},
removeContact: function(e) {
this.model.destroy();
}
});
So which event is fired when a Backbone.Collection removes items internally (e.g. fetch) and how do I listen to it?
When a Collection is fetched and the the model data returns from the server the Collection calls
reset()and fires theresetevent.So is in your
resetbinding where you have to empty() your DOM element. In your case in yourlistContacts().