JavaScript tips
I have been eyeball deep in JavaScript lately, and I've been using two things that have been making life so much easier that I thought they would be good things to share.
The first was inspired by my recent foray with Model-Glue: a function I called trace(). It's rather simple, actually. Instead of adding alert()'s in my code, which in some cases – like loops that run more than a few times – required a ridiculous amount of clicking ok every page-refresh; I added trace(whatever I might normally alert);.
[viewcode] src="javascript_tips.txt" showsyntax=no geshi=javascript[/viewcode]
Then all you have to do is add a textarea control to the first (in my case, only) form on the page, named "trace". Now instead of using alerts I use trace, and instead of clicking ok on 30 popups, I just see 30 lines of text in a text area. It seems like a really simple, really obvious trick – but it's only just occurred to me now, after several years of writing and debugging JavaScript.
The second trick is CFDump… er, JSDump. I found this with a quick google search so again, if you had ever thought, "gee I wish there was a CFDump for JavaScript!" and bothered to search, you've probably seen this.
The article I found was Simple Javascript Object Dump Function by Scott Van Vliet.
[viewcode] src="javascript_tips2.txt" showsyntax=no geshi=javascript[/viewcode]
You may notice that in the post I linked that someone left a comment reporting that Firefox 2 reports an infinite loop. As of today, I've tested in both IE7 and Firefox 2, with no issues and no infinite loops.
His article doesn't give any documentation or examples for how to use it, so I thought I would.
/* @obj - any JavaScript variable/object. @name - the display name you want to give to the root node of the object tree dump. @indent - a string to be used as your indenter. Generally use '\t'. It is appended with '\t' for each level of recursion. @depth - leave blank, defaults to 0. Used for depth checking in recursion. */
And an example:
[viewcode] src="javascript_tips3.txt" showsyntax=no geshi=javascript[/viewcode]
This outputs:
Foo
bar: Hello, world!
success: true
count: 50
anotherObj
bar: Hello, world!
count: 100
success: true
Of course, I can't write this post mostly about JSDump without mentioning this amazing JSDump utility that was inspired by CFDump, and looks nearly the same, if not better. I haven't had a chance to play with it yet, because the above function was simpler and more than sufficient. It even paired nicely with my trace function above. But Rey Bango really deserves a lot of credit for taking the idea and running with it.
Posted in JavaScript