I have a Backbone View for a general element that specific elements will be inheriting from. I have event handling logic that needs to be applied to all elements, and event handling logic that is specific to child-type elements. I’m having trouble because a child View has its own callback for an event that is also handled by the parent View, and so when I try to use the events hash in both, either the child or parent callback is never called. Let me illustrate with some code:
var ElementView = Backbone.View.extend({
events: {
"mouseup": "upHandler",
"mousedown": "downHandler",
"mousemove": "moveHandler"
},
initialize: function() {
// add events from child
if (this.events)
this.events = _.defaults(this.events, ElementView.prototype.events);
this.delegateEvents(this.events);
}
});
var StrokeView = ElementView.extend({
events: {
"mousemove": "strokeMoveHandler"
}
});
How would I solve this in an extensible way, especially if I will later have another level of inheritance?
One way to handle this would be to use “namespaces” for events:
In fact, this approach is suggested in Backbone.js documentation.