User Tools

Site Tools


technical_notes:public:20130929-backbone-identify-events-leak

Parent

Backbone - How to resolve events leak (refere as Memory leak)

In backbone, when you create a reference for a view, it declares events. If the view is not destroyed properly when our program replace it, we get a trace of the reference and the events are already binded.

It has been called Zombie view by Derick Bailey 1).

The resulting memory leaks are like the zombies of the movies – hiding in dark corners, waiting to jump out and eat us for lunch.

The view has to managed it ressources

In backbone it's the view that is responsible for initiating events. You have to give it the responsability of closing them events. Be careful to not forget the parent and the linked model.

To fix this issue, Derick Bailey propose to extend backbone model :

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

The onClose is a callback that lets you set your own traitments to unbind models :

MyView = Backbone.View.extend({
  initialize: function(){
    this.model.bind("change", this.render, this);
  },
  render: function(){ ... },
 
  onClose: function(){
    this.model.unbind("change", this.render);
  }
 
});

To finish, you have to implement a simple view manager we will use in the router :

function AppView(){
 
   this.showView(view) {
    if (this.currentView){
      this.currentView.close();
    }
    this.currentView = view;
    this.currentView.render();
 
    $("#mainContent").html(this.currentView.el);
  }
 
}

Here is the implementation in the router :

MyRouter = Backbone.Router.extend({
  routes: {
    "": "home",
    "post/:id": "showPost"
  },
 
  initialize: function(options){
    this.appView = options.appView;
  },
 
  home: function(){
    var homeView = new HomeView();
    this.appView.showView(homeView);
  },
 
  showPost: function(id){
    var post = posts.get(id);
    var postView = new PostView({model: post});
    this.appView.showView(postView);
  }
});

More :

technical_notes/public/20130929-backbone-identify-events-leak.txt · Last modified: 2013/10/06 18:43 by Fabien Arcellier