Last Updated: February 25, 2016
· shovon

Deleting a Backbone Model Without Sending a DELETE Request

I've been using Backbone.js for more than just server-client apps. I catch myself using Backbone's views, models, and collections for nothing but front-end elements that absolutely don't need to meddle with the back-end.

Backbone's Model, though, doesn't support destroying itself, without sending a DELETE request to the server.

However, Backbone's Collection listens for a destroy event to be triggered by a model. Hence, you can manually trigger that from your model, and your collection will happily delete it.

Let's initialize a new instance of Backbone's default Collection.

var myCollection = new Backbone.Collection();

And then, say, you add three records to the collection.

  { name: "Mike"},
  { name: "John" },
  { name: "Alex" }

Somehow, you managed to get a hold of the reference to the model that has its name attribute set to "John".

var john = myCollection.at(1);

Now, you want to delete it, but you seem to not have a reference to myCollection.

Well, you'll just trigger its destroy event, while passing the model as a parameter.

john.trigger('destroy', john);

There you have it. Deleting models, without making a DELETE request to the server.


Just like what @nono said in the comment, below, you can equally call remove on a model's collection property--which happened to be a reference to the collection that the model is a member of. Calling remove will not make an AJAX request to the server.

Say Thanks

6 Responses
Add your response


Why not just doing john.collection.remove(john);?

over 1 year ago ·

@nono: that's definitely a good option.

over 1 year ago ·

the only difference is that @nono's solution will work on collection object only. while the
@shovon's way will "bubble" to every collection the model belongs.

over 1 year ago ·

@oak-tree thanks for that.

over 1 year ago ·
84f3c24f0fabee906bb4cdb59d628cd7 normal

works good :) , nice post.

over 1 year ago ·

For models without collections it also works.
f.e. in View:
this.model.trigger('destroy', this.model);

over 1 year ago ·