ifnwdg
Last Updated: February 25, 2016
·
16.71K
· shovon
2edd809f45e37c99eefbd6e7c969b52a

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.

myCollection.add([
  { 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.

[EDIT]

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
Respond

6 Responses
Add your response

3169
52143950e2745d7321b597d2615ca90a

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

over 1 year ago ·
3199
2edd809f45e37c99eefbd6e7c969b52a

@nono: that's definitely a good option.

over 1 year ago ·
11740
A898041222e5e951186a87b0a556afd1

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 ·
11757
2edd809f45e37c99eefbd6e7c969b52a

@oak-tree thanks for that.

over 1 year ago ·
13850
84f3c24f0fabee906bb4cdb59d628cd7 normal

works good :) , nice post.

over 1 year ago ·
15156
09c78284335b7efc6d88a73bac42c191

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

over 1 year ago ·