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
JS
define('views/base-view', ['backbone', 'underscore'], function (Backbone, _) {return Backbone.View.extend({inheritEvents: function (parent) {var parentEvents = parent.prototype.eventsif (_.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
JS
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 ParentViewthis.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.