Last Updated: February 25, 2016
·
15.28K
· brianerickson

Don't let your Backbone.js views grow up to be Zombies!

Picture

Since its almost Halloween, I thought this would be a timely tip. It also happens to be one of Backbone.js articles I reference the most:

The key is implementing a 'close' method on all Backbone views:

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

The main thing to watch out for is assigning multiple views to the same DOM element (take it from me - this is bad!), calling close() will destroy that shared element. For example, this is the BAD WAY:

MyPage.Views.List = Backbone.View.extend({
    el : '#mypage'
});

Instead, it's better to let the view create its own root element (which you can change with the 'tagName' property) and place it where you want it in the DOM, preferably with this.$el.html(myPage) or this.$el.append(myPage) in the parent view.

Or if you are starting a fresh Backbone.js project, you can save yourself a lot of headache and use the excellent Backbone LayoutManager project.

3 Responses
Add your response

Nice tip. But, shouldn't you use

this.trigger('close')

instead of

if (this.onClose){
this.onClose();
}
??

over 1 year ago ·

@fatmuemoo It is extra clean-up function that must be defined if you bind events manually in initialize method (helps to get rid of this.on('close', this.onClose, close))

over 1 year ago ·

We just updated to Backbone.js 0.9.10 and I'm happy to see they added some methods to handle this problem. From the backbone.eventbinder README:

"Backbone v0.9.9 introduced two new methods to the Backbone.Events object: listenTo and stopListening. These methods are direct replacements for Backbone.EventBinder."

over 1 year ago ·