Max SchmittMS
28th October 2013

How to Inherit Events from Backbone Views

Today I needed a way to inherit events from a parent view using Backbone. I found a great solution on Stack Overflow and here's how I implemented it. The code examples in this post assume you're using RequireJS for AMD but of course the solution also works with plain Backbone.

All my views inherit from a view called BaseView:

BaseView

define('views/base-view', ['backbone', 'underscore'], function(Backbone, _) {
return Backbone.View.extend({
inheritEvents: function(parent) {
var parentEvents = parent.prototype.events
if (_.isFunction(parentEvents)) {
parentEvents = parentEvents()
}
this.events = _.extend({}, parentEvents, this.events)
}
})
})

The inheritViews-method is key here. Now if you want to extend a view from another including all events, you can do the following:

ChildView

define('views/child-view', ['views/parent-view'], function(ParentView) {
return ParentView.extend({
events: {
'click #start-button': '_start'
},
initialize: function() {
ParentView.prototype.initialize.apply(this, arguments)
// inherit all events from ParentView
this.inheritEvents(ParentView)
},
_start: function() {
console.log('Starting')
}
})
})

That's it! Make sure you call inheritEvents in the constructor and that ParentView extends BaseView (or another view that extends BaseView). Otherwise, inheritEvents will not be available to you.

Image of my head

About the author

Hi, I’m Max! I'm a fullstack JavaScript developer living in Berlin.

When I’m not working on one of my personal projects, writing blog posts or making YouTube videos, I help my clients bring their ideas to life as a freelance web developer.

If you need help on a project, please reach out and let's work together.

To stay updated with new blog posts, follow me on Twitter or subscribe to my RSS feed.