Wednesday, December 1, 2010

XJS: Using the debugger command to start a debugging session

The ability to kick of the an in-line step-by-step debugger was introduced in JavaScript early on. Since before JS version 1.5, I believe. However, practically speaking there were few client-side debuggers that could take advantage of this.
Thus, the use of it has not been heavy even after the more ready availability of Browser development support and in-line debuggers. Today, all browsers support some sort of step-by-step debugger that can be used in concert with the debugger command to more effectively debug code, so perfect time to remind us of this option.

Why would we need to use it?. Let use this snippet as an example:

for (var i=0; i <= 10000; i++) {   
if (i==98) {

Using conventional in-line debugging you would have to set a break-point, then iterate along until you reached the loop condition that you were interested in, i.e. 98. Using the debugger statement, you simplify this drastically.

Expanding this principle into use with ExtJS is easy. Giving the nested nature of much of the ExtJS code and heavy use of complex configuration objects setting breakpoints is sometimes a game of hit-and-miss.
Using the debbuger statement you will still able to halt the execution at the right place even if you did not hit the correct break-point in your debugging tool.

For example:

 1: listeners: {
2: render: {
3: fn: function(){

4: //stop for debugging here

9: //Kick off the clock timer that updates the clock el every second:
//Would need to be set in application format

12: run: function(){
13: Date().format('g:i:s A'));

14: },
15: interval: 1000
16: });

17: },
18: delay: 100
19: }
20: }

Here we can stop when then rendering is activated to investigate code execution further.

The debugger statment works in most browsers, i.e. Firefox with Firebug, IE 8, Chrome. In IE you will have to explicitly put the browser in debugging mode by clicking the "Start Debugging" button in the developer tools.

Happy Debugging,

No comments: