Preslav Rachev
Preslav Rachev

Reputation: 4003

Recycling views in Backbone.JS

I work on a Backbone app, which utilizes a lot of view. I fell into the (usual I think) trap of instantiating a Router (sort of, the main controller) which is responsible for clearing out the views, instantiating new ones, and filling them with data. I say trap, because although JavaScript has a built-in garbage collector, one will quickly start noticing how the usability of the app gets hampered by the many unused views which still reside somewhere in memory.

I wish there were a way to recycle those views. I thought that this would be as easy as calling initialize() on the view with a new model, and then rerender. This is unfortunately not as easy.

Also, one would have to kinda "destroy" the view handles, for example, event handlers and stuff...

What would be a good practice to do this?

Upvotes: 1

Views: 960

Answers (1)

uadnal
uadnal

Reputation: 11435

Once a view has been removed from the DOM it will be garbage collected. Unless of course you cache it. If you do cache a view and remove it from the DOM, all event handlers are garbage collected as well. Unless you use something like jQuery's detach method, which will preserve the event handlers.

http://api.jquery.com/detach/

If you want to recycle a view, simply cache it in a variable.

Inside your router's init method, do something like this:

this.views = {};

Then whenever a route is called check if the name of the view is available in the cache and if it is, use that, otherwise create a new one.

someRoute: function () {
   var view;
   if ( _.has(this.views, 'someRouteView') ) {
        view = this.views.someRouteView;
   } else {
        view = new SomeRouteView;
        this.views.someRouteView = view;
   }
   // You have a view now
}

Again, if you don't create a new view, you will have to use something like jQuery's detach method to preserve event handling.

Upvotes: 3

Related Questions