Search code examples
javascriptbackbone.jsmemory-management

How to ensure proper closing of backbone views


I have a close function attached to all of my views,

Backbone.View.prototype.close = function()
{
  this.remove();
  this.unbind();

  if (this.closeMe) this.closeMe();
};

And in closeMe() function inside views I call off() function of backbone to remove previously-bound callback function from models and collections.

closeMe: function()
   {     
     if(this.model)
        this.model.off(null, null, this);
     ...
   }

Question is, If I have some variables attached to current view in initialize function, Do I need to handle them via closeMe() function?

 initialize : function(options)
    {
     ...
     this.myVar= options.something;  
    }

Solution

  • The garbage collector do this work for you.

    The garbage collector algorithm reduces the definition of "an object is not needed anymore" to "an object has no other object referencing to it". An object is considered garbage collectable if there is zero reference pointing at this object.

    When the reference to the view has zero reference pointing at it, the garbage collector will delete this object. At this moment, if the object myVar has no references pointing at it, the garbage collector will delete it.

    By the way, I suggest to use the method listenTo to listen events instead of method on because simplify your code. When you call remove on Backbone View, removes a view from the DOM, and calls stopListening over the view to remove any bound events that the view has listenTo'd.