This question is just out of curiosity. I want to know how jquery\'s .click() works behind the scenes.
For instance if I create a button:
It will depend on the browser.
If you're using a browser that supports addEventListener(), they'll add a handler using that.
Although I'm pretty sure they're actually attaching a function that first repairs/normalizes the event object, then checks the DOM element for the jQuery12345... property and looks up the handler in jQuery.cache and invokes it.
If you log your element to the console, you'll see a property that looks something like:
jQuery1296081364954: 1
Then if you log that number to the console from jQuery.cache, you'll see the associated data.
console.log(jQuery.cache[1]);
...which will give a structure something like this:
{
events:{
click:[
{ /* object containing data relevant to the first click handler */ }
]
},
handle:{ /* this may be what initially gets called. Not sure. */ }
}
Because jQuery does normalize the event object, it isn't quite as simple as just assigning a a handler for you and calling it. I believe it is also done with the cache in order to avoid memory leaks in older browsers.