Disposing of view and model objects in Backbone.js

you’re on the right path. you should have an object that controls the lifecycle of your views. i don’t like to put this in my view. i like to create a separate object for this.

the thing you need to do, is unbind the events when necessary. to do this, it’s a good idea to create a “close” method on all of your views, and use the object that controls the lifecycle of everything to always call the close method.

for example:


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

at this point, you would set up your code to only have one instance of the AppController, and you would always call appController.showView(...) from your router or any other code that needs to show a view in the #someElement portion of your screen.

(i have another example of a very simple backbone app that uses an “AppView” (a backbone view that runs the main portion of the app), here: http://jsfiddle.net/derickbailey/dHrXv/9/ )

the close method does not exist on views by default, so you need to create one yourself, for each of your views. There are two things that should always be in the close method: this.unbind() and this.remove(). in addition to these, if you are binding your view to any model or collection events, you should unbind them in the close method.

for example:


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

    modelChanged: function(){
      // ... do stuff here
    },

    close: function(){
      this.remove();
      this.unbind();
      this.model.unbind("change", this.modelChanged);
    }
  });

this will properly clean up all of the events from the DOM (via this.remove()), all of the events that the view itself may raise (via this.unbind()) and the event that the view bound from the model (via this.model.unbind(...)).

Leave a Comment