I did something similar using faux- super JavaScript, as mentioned in the Backbone.js documentation , and the initialization function
var ElementView = Backbone.View.extend({ events: { "mouseup": "upHandler", "mousedown": "downHandler", "mousemove": "moveHandler" }, initialize: function() { this.delegateEvents(); } }); var StrokeView = ElementView.extend({ initialize: function() { this.events = _.extend({}, this.events, { "mousemove": "strokeMoveHandler" }); // Call the parent initialization function ElementView.prototype.initialize.call(this); } }); var SubStrokeView = StrokeView.extend({ initialize: function() { this.events = _.extend({}, this.events, { "click": "subStrokeClickHandler", "mouseup": "subStrokeMouseupHandler" }); // Call the parent initialization function StrokeView.prototype.initialize.call(this); } }); var c = new SubStrokeView(); console.log(c.events); // Should be something like // click: "subStrokeClickHandler" // mousedown: "downHandler" // mousemove: "strokeMoveHandler" // mouseup: "subStrokeMouseupHandler"
The magic happens by setting events in the initialize function. If your prototypes have several events attributes, JavaScript will only see the one that was installed most recently due to how prototyping works.
Instead, doing it this way, each view sets its own this.events , then calls its parent function initialize , which in turn extends this.events with its events, etc.
You need to install this.events as follows:
this.events = _.extend({}, this.events, ...new events...);
instead
_.extend(this.events, ...new events...);
Performing this second method will create an event object in the parent ( ElementView ) prototype. The first method ensures that each model gets its own copy.
source share