Destroying a Backbone Model in a Collection in one step?
34,629
Solution 1
Model.bind("remove", function() {
this.destroy();
});
...
var model = new Model();
...
collection.remove(model);
Removing a model from a collection triggers the "remove"
event.
So if you want to, you can get models to bind to them and destroy themselves.
Solution 2
Calling collection.reset() without passing any models as arguments will empty the entire collection.
http://backbonejs.org/#Collection-reset
Comments
-
yves amsellem almost 2 years
Are these two steps mandatory to delete a Model?
var model = collection.get(id); model.destroy(); collection.remove(model);
Isn't there a way to destroy a model when it is removed from its collection?
-
pooja upadhyay over 12 yearsThanks for this, however it's fairly unintuitive IMO. Is there any reason why you WOULDN'T want a model destroyed when calling remove on the collection (at least enough of a reason for this not to be the default behavior). Is this worth raising as a feature request on github?
-
Raynos over 12 years@kissmyface Collections are arbitary (like in database terms) views over models. If I decide you shouldn't see Model X in View (collection) Y why would model X be destroyed?
-
pooja upadhyay over 12 yearsThat's a nice analogy. I didn't realize that they were quite so decoupled (all my code so far has had quite rigid links between collections and models). Thanks for the clarification.
-
Raynos over 12 years@kissmyface however this doesn't mean we shouldn't have sugar like have with
.create
we could have a.destroy
that destroys and removes a model on a collection -
pooja upadhyay over 12 yearsThat's exactly what I did. I created a destroy method on my controller (takes a id as a param). Inside I destroy the model and then remove it from the collection - it works great.
-
Henry almost 12 yearsI tried this, but
destory()
will invoke theremove
event again, andremove
event will invokedestory()
again, so it ends up calling sync twice. Is this expected?