I can attach handlers to Backbone Views like:
var TodoView = Backbone.View.extend({
events: {
"xxx": "eventHandler1"
"yyy": "eventHandler2"
}
});
But what if I want to attach more than 1 handler to the same event?
var TodoView = Backbone.View.extend({
events: {
"xxx": "eventHandler1"
"yyy": "eventHandler2"
"xxx": "eventHandler3" // this isn't valid ... at least in CoffeeScript
}
});
I could create a custom handler like
function compositeXXX() { eventHandler1(); eventHandler2 }
But this doesn’t seem ideal …
This:
won’t work because
eventsis an object literal and you can have at most one (key,value) pair in an object. That would probably be the same as saying:This CoffeeScript:
is functionally identical to the JavaScript version and won’t work for the same reason.
Andy Ray’s idea of using
won’t work either as Backbone won’t understand that it should split the value on whitespace; similarly, this:
won’t work because Backbone doesn’t know what to do with an array in this context.
Views bind their events through
delegateEventsand that looks like this:So
methodstarts out as the value for'event selector'. If it is a function from something like:then it is used as-is, otherwise it is converted to a property of
this:If one were bold, one could adjust
delegateEventsto understand an array or whitespace delimited string:A fairly simple patch like that would allow you to use a whitespace delimited list of handlers:
or an array of handlers:
or even a mixed array of method names and functions:
If you don’t want to patch your Backbone or forward such a patch to the Backbone maintainers then you could go with your original “manual dispatching” idea: