Accessing functions bound to event handlers with jQuery
Solution 1
Edit: the method below works only in jQuery < 1.7
You can find a lot of interesting tips and tricks in this article: Things you may not know about jQuery.
It seems that jQuery uses data
to store event handlers:
You can access all event handlers bound to an element (or any object) through jQuery’s event storage:
// List bound events:
console.dir( jQuery('#elem').data('events') );
// Log ALL handlers for ALL events:
jQuery.each($('#elem').data('events'), function(i, event){
jQuery.each(event, function(i, handler){
console.log( handler['handler'].toString() );
});
});
// You can see the actual functions which will occur
// on certain events; great for debugging!
Solution 2
jQuery 1.7 has stopped exposing the events in the regular data() function. You can still get them like this:
var elem = $('#someid')[0];
var data = jQuery.hasData( elem ) && jQuery._data( elem );
console.log(data.events);
Please note, that this only works for Events which have been bound using jQuery. AFAIK you there is no way to see all the events which have been bound using the regular DOM functions like addEventListener.
You can see them in the webkit inspector though: In the Elements tab navigate to the desired DOM node, on the right side select the "Event Listeners" drop down.
googletorp
I'm a senior Drupal developer, working as a consultant for Reveal IT. Over the past year I've spent a lot of time on Drupal and Drupal Commerce, created a lot of different sites with it and enjoyed it all the way. I maintain or co-maintain a host of modules on drupal.org and have contributed to a lot of other modules. Recently I've started contributing to Drupal core, making me in the top 5% of most contributions. When I'm not doing work or Drupal related stuff, I usually spend time with my beautiful wife and amazing son, play soccer, make grandiose cakes or some other fun stuff.
Updated on October 21, 2020Comments
-
googletorp over 3 years
With jQuery you can bind functions to an event triggered on a DOM object using
.bind()
or one of the event handler helper functions.jQuery have to store this internally somehow and I wonder if is it possible given a DOM object, to find out which events have been bound to the object, and access those functions etc. The desired return result could look something like this:
{ click: [function1, function2], change: [function3], blur: [function4, function5, function6] }