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

Share:
34,629
yves amsellem
Author by

yves amsellem

Jongo developer — Query in Java as in Mongo shell

Updated on July 09, 2022

Comments

  • yves amsellem
    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
    pooja upadhyay over 12 years
    Thanks 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
    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
    pooja upadhyay over 12 years
    That'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
    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
    pooja upadhyay over 12 years
    That'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
    Henry almost 12 years
    I tried this, but destory() will invoke the remove event again, and remove event will invoke destory() again, so it ends up calling sync twice. Is this expected?