jashkenas / backbone

Give your JS App some Backbone with Models, Views, Collections, and Events
http://backbonejs.org
MIT License
28.09k stars 5.38k forks source link

Can't bind listener to multiple event in event hash #2524

Closed keshin closed 11 years ago

keshin commented 11 years ago

I want to bind a listener to multiple event via the events hash in a view, but doesn't work.

events: {
  "click change .button": "change"
}

It looks like backbone treat the second event type as a part of the selector, which lead the binding failed.

zyzniewski commented 11 years ago

http://backbonejs.org/#View-delegateEvents

Events are written in the format {"event selector": "callback"}

keshin commented 11 years ago

@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"
}
srcspider commented 11 years ago

@keshin to me the so called "not so elegant" one looks a lot easier to read.

keshin commented 11 years ago

@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).

srcspider commented 11 years ago

@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.

keshin commented 11 years ago

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);
  }
});