Closed keshin closed 11 years ago
http://backbonejs.org/#View-delegateEvents
Events are written in the format
{"event selector": "callback"}
@zyzniewski My case is, I want to bind a listener to multiple events of an element. In jQuery, I just need to
$("#myel").on("change blur", myListener);
But in Backbone, I have to write in this way:
events {
"change #myel": "myListener",
"blur #myel": "myListener"
}
That's acceptable, but not so elegant in my opinion.
If possible, I hope the format can support multiple events with comma separated, like the code below:
events {
"change,blur #myel": "myListener"
}
@keshin to me the so called "not so elegant" one looks a lot easier to read.
@srcspider It's fine for 2 events case, but I don't think it's still easier to read for 3 events or even more(the probability is very small but it is possible).
@keshin personally when maintaining/inspecting code I almost always prefer it to be more explicit then less explicit or in need of "eye parsing" to decipher the meaning (it's easier to comment/note that way too). The comma separated list is cryptic, especially when the comma is not an invalid selector character itself. It's also easier to change/refactor code that's layed out, compared to code that has been canned to a single line.
I do agree that sometimes it is favorable to compact code since having a lot less code is easier to scan though, I just don't believe this to be the case in this case. I think this sort of magic should be allowed to be hooked in, but not part of the default distribution.
Just my 2 cents.
Thanks for your comments @srcspider I find a way to hook in the customized events hash, correct me if I was wrong
var MultipleEventView = Backbone.View.extend({
delegateEvents: function(events) {
var parsedEvents = _.clone(events);
// parse the multiple events binding
// call the super delegateEvents
Backbone.View.prototype.delegateEvents.call(this, parsedEvents);
}
});
I want to bind a listener to multiple event via the events hash in a view, but doesn't work.
It looks like backbone treat the second event type as a part of the selector, which lead the binding failed.