Access events of a DOM node jQuery
20 April 2013
Ever wondered how and where jQuery stores event handlers for a dom node
and how we can access all the event handlers ?
jQuery stores event handlers for a dom node in the events store. It can be accesses via the data
method of the dom node.
Lets look at an example:
function clickHandler1(){ } function clickHandler2(){ } var $body=$("body"); $body.bind("click",clickHandler1); $body.bind("click",clickHandler2); console.log($("body").data("events"));
The result of the above code is as follows:
What do we conclude?
The result shows an object having key as click
and value as Array
of objects which represent each handler. Each handler object has various properties, one of them is handler which points to the function bound to the event. Object also has namespace, tyep etc important properties.
Learnings/Tips
We have to be careful while binding and unbinding event handlers to a DOM.
For example:
$("body").bind("click",function(){ alert("1"); }); $("body").unbind("click",function(){ alert("1"); });
<p>
After executing above an alert will be thrown when we click on body. Why?
</p>
<p>
The reason is jQuery keeps a map of event and event handlers. When we execute the above code, a single event handler is attached to the body node with anonymous function attached to it. When we unbind the anonymous function from the click event, its not the same function we binded. So as its a different function the prev function is not removed and we get an alert when we click on body.
</p>
<h4> How to fix it?</h4>
<p>
We can do something like this
function clickHandler(){ } $("body").bind("click",clickHandler); $("body").unbind("click",clickHandler);
<p>
In the above snippet we are binding and unbinding the same function <code>clickHandler</code> and hence it works :)
</p>
</p>
blog comments powered by Disqus