13

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!!

4
  • possible duplicate stackoverflow.com/questions/10400630/… Commented May 7, 2012 at 21:30
  • Gone from where? A collection? The document? The browser's memory? Commented May 7, 2012 at 21:37
  • @JMM yep gone from everywhere, avoiding every gotcha, every zombie binding. I'm looking for a full guide to removing and destroying everything and ensuring the model is garbage collected. Commented May 7, 2012 at 21:48
  • 2
    @Larry Battle not a duplicate of that question at all... Commented May 7, 2012 at 21:48

1 Answer 1

11

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.

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.