[thelist] just a tip on js

VOLKAN ÖZÇELİK volkan.ozcelik at gmail.com
Fri Aug 5 08:34:30 CDT 2005


<tip type="Javascript Debugging" author="Volkan Ozcelik">
Javascript debugging is *most of the time* done by placing "alert"s all around.

This has several side-effects:

1. If you have a lot of async javascript callbacks (setintervals, settimeouts);
an alert will delay some of them: hence change the order of execution
of calls. So it will be hard to re-generate an existing problem.

2. you may forget commenting out (or removing) "alert"s at your
production server. Although it is a small detail for the developer, it
is very annoying for the user.
And it will degrade your client's trust (they will think that you are
leaving your messy code all around. If this happens several more times
and your client is a very strict/though one, chances are that you will
lose your client.
-1 for your charisma and reputation :) )

To handle these issues you may launch a separate debugger window and
modify its innerHTML instead of alerting things. Here is a snippet for
it:

var Debugger = {
	attach:function() {
		alert("begin: attaching debugger.");
		document._debugWindow = window.open("/webRoot/debugPane.html");
		alert("debugger attached.");
                                this._attached = true;
	},
	println:function(strWhat){
                               if(!this._attached) return;
		if(!strWhat) {strWhat = "";}
		document._debugWindow.document.getElementById('x').innerHTML =
			document._debugWindow.document.getElementById('x').innerHTML + "<br />" +
			strWhat;
	},
	clear:function() {
                               if(!this._attached) return;
		document._debugWindow.document.getElementById('x').innerHTML = "";
	}
}

Debugger.attach();

* * *
instructions to follow:

1. Just make sure that debugPane.html exists, its path is correct, and
there is an element (ideally a "pre") with id "x" in it.

2. Make sure that you comment out "Debugger.attach();"
in production server

             //Debugger.attach();

3. When you want to print a debug statement to the console use:

Debugger.println("my debug statement is " + somevariable to be debug);

and it will appear on the debug window.

4. When you want to clear everything use "Debugger.clear();"

p.s.:
I have not fully tested the code, it may need some fine-tuning but it
should give
an idea on the general approach to the problem.
</tip>


More information about the thelist mailing list