Following code has been tested with jQuery 1.3 .
Let's say that I have bound all the links to display an alert.
1$("a").bind("click", function (e) { 2 e.preventDefault(); 3 alert("clicked"); 4});
Mine is a large application and a co-worker has added another javascript file which does this
1$("a").bind("click", function (e) { 2 e.preventDefault(); 3 alert("hello"); 4});
Now if I click on a link I get two alerts. Not good. One way to debug would be to go through all the included javascript files.
However it would be cool if there is a way to find all the click handlers associated with an element.
jQuery has data method which it uses internally to store information. jQuery uses data method to store all the handlers associated with an element. We could use this information to our advantage. Here I am trying to find out all the click handlers associated with the first link.
1var output = jQuery.data($("a").get(0), "events"); 2 3jQuery.each(output.click, function (key, value) { 4 alert(value); 5});
The output looks like this
1function (e) { e.preventDefault(); alert("clicked"); } 2function (e) { e.preventDefault(); alert("hello"); }
jQuery.data method is also very useful if you want to store some information about an element. For example, in an application you need to store information about people. In the html page you are only displaying names. And when a name is clicked then you want to display age, hometown and the company they work for. You can store information about each user using jQuery.data and you can retrieve it when username is clicked.