Tuesday 29 May 2012

JQuery event debugging

http://james.padolsey.com/javascript/debug-jquery-events-with-listhandlers/

CODE

Here’s a useful debugging plugin for jQuery. It will list the handler/’s of any event bound to any element:

/ UPDATED -> NOW WORKS WITH jQuery 1.3.1
$.fn.listHandlers = function(events, outputFunction) {
return this.each(function(i){
var elem = this,
dEvents = $(this).data('events');
if (!dEvents) {return;}
$.each(dEvents, function(name, handler){
if((new RegExp('^(' + (events === '*' ? '.+' : events.replace(',','|').replace(/^on/i,'')) + ')$' ,'i')).test(name)) {
$.each(handler, function(i,handler){
outputFunction(elem, '\n' + i + ': [' + name + '] : ' + handler );
});
}
});
});
};

USAGE


It’s pretty simple to use, you can specify the elements (as you usually would, via a selector), the events to be listed and the output function to which the plugin will feed the data.

If you’re using firebug then it’s best to use either the console.log function or console.info.

// List all onclick handlers of all anchor elements:
$('a').listHandlers('onclick', console.info);   // List all handlers for all events of all elements:
$('*').listHandlers('*', console.info);   // Write a custom output function:
$('#whatever').listHandlers('click',function(element,data){
$('body').prepend('<br />' + element.nodeName + ': <br /><pre>' + data + '<\/pre>');
});

Note, this will only work if you’ve used jQuery’s native event registration methods, e.g.$(elem).click() / $(elem).bind('click').

image

No comments:

Post a Comment

How to find the last interactive logons in Windows using PowerShell

Use the following powershell script to find the last users to login to a box since a given date, in this case the 21st April 2022 at 12pm un...