Don't let your Backbone.js views grow up to be Zombies!
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:
- Zombies! RUN! (Managing Page Transitions In Backbone Apps) http://lostechies.com/derickbailey/2011/09/15/zombies-run-managing-page-transitions-in-backbone-apps/
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.
- image credit: TheDarkCloak
Written by Brian Erickson
Related protips
3 Responses
Nice tip. But, shouldn't you use
this.trigger('close')
instead of
if (this.onClose){
this.onClose();
}
??
@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)
)
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."