Search code examples
collectionsmodelbackbone.js

Destroying a Backbone Model in a Collection in one step?


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?


Solution

  • 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.