Posts Tagged ‘Debugging’

Debug jQuery events with ‘listHandlers()’

Posted in 'Code Snippets, JavaScript' by James on January 8th, 2009

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

The Code:

// 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.

Debugging with $.log() or log()

Posted in 'Code Snippets, JavaScript' by James on December 30th, 2008

I always found myself forgetting to remove the numerous console.log calls within my scripts after debugging so I created a little jQuery plugin to deal with it. If the user has no console it won’t fail, so there’s no need to worry anymore!

The Code:

$.log = $.fn.log = function(o) {
 
    window.console && console.log ?
        console.log.apply(console, !!arguments.length ? arguments : [this])
    : opera && opera.postError
        && opera.postError(o || this);
 
    $.log.cache = $.log.cache || [];
    $.log.cache[$.log.cache.length] = arguments.length > 1 ? arguments : o || this;
    return $.log.cache.length-1;
 
}

It’s a pretty concise plugin, it will check for the presence of a console or the equivalent utility in Opera and if present will post a log/error, otherwise it will exit smoothly… It will also save a cache of the log accessible as a property: ($.log.cache).

Usage:

// Log: Method #1
$.log('Log this message.');
 
// Log: Method #2
$('a').log(); // Logs all anchors
 
// Reading the cache:
// The log cache is an array, you can access it like this:
var logArray = $.log.cache;
 
// Or, to access a specific log:
var logIndex = $('div').log(); // Returns index of log
alert( $.log.cache[logIndex] );

Non-jQuery:

If you’re not using jQuery then this simple log function does the same:

window['log'] = function(o) {
 
    window.console && console.log ?
        console.log.apply(console, !!arguments.length ? arguments : [this])
    : opera && opera.postError
        && opera.postError(o || this);
 
    window.log.cache = window.log.cache || [];
    window.log.cache[window.log.cache.length] = arguments.length > 1 ? arguments : o || this;
    return window.log.cache.length-1;
 
}
 
// Log something:
log('Blah blah blah');
 
// Retrieve cache:
alert(log.cache);

I hope you find this useful!