Mar 7, 2010

jQuery event binding internal

The event binding in jQuery is very interesting. It is designed with several goals. 1. It should works consistently across browsers. 2. It should allows attaching more than one handler function to a event. The event registration information is saved in a jQuery.data(elem). In jQuery.cache actual data store for all these data. A piece of data in the cache can be assigned to the element. Below is some pesudo code to demonstrate the data structure

function fn(..){..}
fn.guid = ..

handleObject = { data: ..,
                 guiid: ..,
                 namespace: "..",
                 type: "click",
                 handler : fn
                 }

clickEventHandlers = handleObject[];

eventsOfElem = [ clickEventHandlers, dblClickEventHandlers, .. ];

elemData = jQuery(elem);

elemData = { events :eventsOfElm, handle : bindingFn }

functionBindingFn = function (..)
{
   jQuery.event.handle.apply(eventHandle.elem, arguments );
}

elem.addEventListener( type, functionBindingFn , false );