Debugging javascript code is not always easy, you have your normal programming flow, but you also have a bunch of event listeners attached to DOM elements that do not really follow a specific pattern.

Hunting listeners in JS files can be quite tedious, this is where the AOP plugin can help you.

What is Aspect Oriented Programming? (AOP)

“In computing, aspect-oriented programming (AOP) is a programming paradigm which isolates secondary or supporting functions from the main program’s business logic. It aims to increase modularity by allowing the separation of cross-cutting concerns, forming a basis for aspect-oriented software development.”

A good AOP article

In javascript, using this technique, you can bind listeners to any function or object, which will be fired when the function is executed. With this information, you can know when a function is executed and what DOM element fired it.

The jQuery AOP plugin is very small and it allows to add advices (Before, After, After Throw, After Finally, Around and Introduction) to any global or instance object.

View demo

* Have your firebug or developer console open

How to use it

Using the plugin is pretty simple, first add the script to your head (you can download it here)

An example:

jQuery.aop.before( {target: String, method: 'replace'}, 
  function(regex, newString) { 
    console.log("About to replace string '" + this + "' with '" + newString + "' using regEx '" + regex + "'");

When a string is replaced you will have this log fired, pretty sweet.

Lets add a little twist to it

What if we want to test any function easily?

var debug = {
	customConnect : function(instance){
		jQuery.aop.before( {target: eval(instance.object), method: instance.method}, function(object) { 
		    console.log('Function Fired : ' + instance.object + "." + instance.method ); 
		    console.log("DOM caller : "); 
		    console.log("object state : "); 

As you can see, you can now bind basically everything using this method. Want to know when your lightbox is fired? Or maybe when this particularly function is called? Pretty easy.

		debug.customConnect({"object": "appModal", "method": "load"})
		debug.customConnect({"object": "window", "method": "test"})  // to test an inline function

That would be how you use it. In this example I fire logs before loading my lightbox and before using the test() function.

That’s it

This is just a start, you could also log any DOM modification, this plugin can really give you a lot of debugging power.

Download the source code View demo

7 thoughts on “Using the jQuery AOP plugin to debug your javascript

Comments are closed.