Backbone\'s documentation states:
The events property may also be defined as a function that returns an events hash, to make it easier to programmatic
Wow, lots of answers here but I thought I'd offer one more. If you use the BackSupport library, it offers extend2
. If you use extend2
it automatically takes care of merging events
(as well as defaults
and similar properties) for you.
Here's a quick example:
var Parent = BackSupport.View.extend({
events: {
change: '_handleChange'
}
});
var Child = parent.extend2({
events: {
click: '_handleClick'
}
});
Child.prototype.events.change // exists
Child.prototype.events.click // exists
https://github.com/machineghost/BackSupport
// ModalView.js
var ModalView = Backbone.View.extend({
events: {
'click .close-button': 'closeButtonClicked'
},
closeButtonClicked: function() { /* Whatever */ }
// Other stuff that the modal does
});
ModalView.extend = function(child) {
var view = Backbone.View.extend.apply(this, arguments);
view.prototype.events = _.extend({}, this.prototype.events, child.events);
return view;
};
// MessageModalView.js
var MessageModalView = ModalView.extend({
events: {
'click .share': 'shareButtonClicked'
},
shareButtonClicked: function() { /* Whatever */ }
});
// ChatModalView.js
var ChatModalView = ModalView.extend({
events: {
'click .send-button': 'sendButtonClicked'
},
sendButtonClicked: function() { /* Whatever */ }
});
http://danhough.com/blog/backbone-view-inheritance/
The soldier.moth answer is a good one. Simplifying it further you could just do the following
var ChildView = ParentView.extend({
initialize: function(){
_.extend(this.events, ParentView.prototype.events);
}
});
Then just define your events in either class in the typical way.