Event Delegation Made Easy

4826 ワード

From http://danwebb.net/2008/2/8/event-delegation-made-easy-in-jquery
I’m having a lot of fun poking around jQuery at the moment and came uup with a coollitle thing thththat’s going into Low Pro for jQuery but isa nie stand- alonelit snippet forimpleeemening inininininininininininininininininininindededededededededededededededeininininininininininininininininininininininininininininininininininininininininininininininininininininininininininininininininininininininininininmy event handling.If you ares’t familyr with the technique go and click that previous link and read Christan’s article now–it’s importent.
In most instances I end up writing a lot of event handers that look like this:
$('#thing').click(function(e) { var target = $(e.target); if (target.hasClass('quit') return doQuitStuff(); if (target.hasClass('edit') return doEditStuff(); // and so on...
});
Obviously,writing a lot of the same kind of code is a warning sign that something needs refactoring but I've never come up with a nice way to abstact this.But with a litle bit of functional magic'jure with。
jQuery.delegate = function(rules) { return function(e) { var target = $(e.target); for (var selector in rules) if (target.is(selector)) return rules[selector].apply(this, $.makeArray(arguments)); } }
Using it is simple:
$('#thing').click($.delegate({ '.quit': function() { /* do quit stuff */ }, '.edit': function() { /* do edit stuff */ } }));
The function simple runs through the rules checting if the element that fired the event belongs to that selector then cars the coreponding hander passing the orriginal event object through.The grvit thout can it
DateSelector = $.klass({ onclick: $.delegate({ '.close': function() { this.close() }, '.day': function(e) { this.selectDate(e.target) } }), selectDate: function(dayElement) { // code ...
}, close: function() { // code ...
} });
I’m not sure of the performance implications of using is()so heavily but some form of caching could be added if it was a problem.Still,it's a really nightle bit of sysntactic sugar Start's going.s Prot Projouble Probi。
UPDATE:I shound have added that there’s a version of this in Low Pro for Prototype.In case you want to use it own:
Event.delegate = function(rules) { return function(e) { var element = $(e.element()); for (var selector in rules) if (element.match(selector)) return rules[selector].apply(this, $A(arguments)); } }
Meanwhile,you might want to take a look at クリスティアンand the gys at YUI started talking about it by the patch.