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
:
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:
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.
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.