Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to delete a backbone model client-side?

What's the best way to delete a model client side? I don't need to worry about removing it server-side. How do I make sure it is removed everywhere, avoiding every gotcha, every zombie binding. I'm looking for a guide to removing and destroying everything and ensuring the model is garbage collected.

Thanks!!

like image 557
fancy Avatar asked May 07 '12 21:05

fancy


1 Answers

It really depends on what is inside this model. If it is binded to events from other instances - View/Collection/Models, you should remove those event listeners manually, since there is no way to remove all of them at once.

Also, Model.destroy() removes the model from any collections ( backbone documents ) :

Destroy model.destroy([options])

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

The thing that you might want to do is assign a new destroy method which includes the event triggering and the stuff you want to remove.

destroy: function(options) {
   // Any events you wish to switch off ( if you have any )
   SomeCollection.off('change', this.changeFn);

   Backbone.Model.prototype.destroy.apply(this, options);       
}

May be you should also be aware of some patterns for making less garbage from Models :

  1. Don't place your initialized model in a variable ( keep it in the collection );
  2. Make sure you write your code in a way that no events are binded from the Model ( Use views/collections for that );
  3. Keep your model code simple, since models in your app will be most numbered.

I think by following those rules you won't need to worry so much about garbage from your Models.

like image 75
drinchev Avatar answered Sep 21 '22 09:09

drinchev