Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Backbone model.destroy(): Is explicit removal from collection necessary?

Tags:

I have a simple question. I am looking at a function with 2 lines of code:

deleteTask: function() {     this.parent.collection.remove(this.model);     this.model.destroy(); } 

If I comment out the first line, which is supposed to remove the model from its collection, things seem to work as intended (as in, the model is removed automatically). From Backbone's website, this is the relevant discription for a model's "destroy" function:

Triggers a "destroy" event on the model, which will bubble up through any collections that contain it.

Am I safe to assume that the removal of this.parent.collection.remove(this.model); will not affect the functionality of the code in any way? This is what I think, but I wanted to make sure of it.

Thank you!

like image 980
AndraD Avatar asked Jan 14 '13 18:01

AndraD


People also ask

How do I remove a model from a collection backbone?

js collection remove is used to remove a model or an array of models from the collection. Syntax: collection. remove(models,options)

What is Backbone js used for?

BackboneJS is a lightweight JavaScript library that allows to develop and structure the client side applications that run in a web browser. It offers MVC framework which abstracts data into models, DOM into views and bind these two using events.

What is Backbone in programming?

Backbone. js is a model view controller (MVC) Web application framework that provides structure to JavaScript-heavy applications. This is done by supplying models with custom events and key-value binding, views using declarative event handling and collections with a rich application programming interface (API).


1 Answers

If you destroy a model, it is removed from any collections that was containing it. You can see that in the backbone source

//Internal method called every time a model in the set fires an event. _onModelEvent: function(event, model, collection, options) {     ...     if (event === 'destroy') this.remove(model, options); 

So yes, I wouldn't think you would need to remove the model from your collection explicitly.

But don't trust me, test for yourself :)

deleteTask: function() {     that = this;     this.model.destroy({       success: function() {         console.log(that.parent.collection);       }     }); } 

Check the console for yourself to see whether the model was removed from the collection.

like image 199
asgeo1 Avatar answered Oct 04 '22 22:10

asgeo1