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.
Written by Salehen Shovon Rahman
Related protips
6 Responses
Why not just doing john.collection.remove(john);?
@nono: that's definitely a good option.
@oak-tree thanks for that.
works good :) , nice post.
For models without collections it also works.
f.e. in View:
this.model.trigger('destroy', this.model);
Have a fresh tip? Share with Coderwall community!
JavaScript on a page runs with the privileges of that origin. One altered library, tag manager, or snippet can read inputs, change what people see, and call your APIs as the user.
Security insights from Cside