Have a look at the jQuery docs for on()
, they explain the concept very well.
Also, you can have a look at the source code!
The lessons learned:
delegate
is just a wrapper foron
with different parameter orderon
does just some parameter normalisation and handlesone
, but delegates then tojQuery.event.add( this, types, fn, data, selector );
event.add
does do a lot of validation, handles multiple types and special cases, pushes the arguments on$.data("events")
and callselem.addEventListener(type, jQuery.event.dispatch, false)
event.dispatch
then queries the handles from$.data("events")
again and builds ajqEvent
from the native event. Then it begins searching for delegated events - the code for that is quite straightforward - and pushes them on thehandlerQueue
, after that the normal handlers which are attached directly on the element. In the end, it just runs thehandlerQueue
, starting with the delegated handlers.