Simple, Yet Powerful Flash Debugging
- By Matthew Donadio
- December 22, 2008
Recently, a PANMA mailing list discussion focused on how to do Javascript to Actionsript communication, and vice-versa. A few people answered, and the topic turned to ExternalInterface in general.
I posted that I have been adding a simple method to all of my classes to pipe out debug info to the browser. I like the method because it is easy to use, and I can see all of my AS and JS debugging in one place. Here it is:
private function debug (… args) {
var msg : String = args.join(" ");
trace(msg);
try {
ExternalInterface.call("console.log", msg);
} catch (e : Error) {
// don’t care
} catch (e : SecurityError) {
// don’t care
}
}
This function relies on having the Firebug extension installed in Firefox, but this is something that most developers have installed anyway. Here’s how it works: It basically builds up a single string from a variable argument list, and calls the Firebug console.log() function via ExternalInterface. The try/catch is there simply because I wanted to be explicit in the fact that ExternalInterface.call() can throw these errors, but I don’t really care if the function fails.
As I mentioned above, I add this method to all of my classes. I then call debug() in place of trace().
So, why not something more elaborate?
Over the years I have written many variants of debug utilities and classes. When I started doing Flash development, I created a debug library and this was turned into an elaborate class.
When we made the switch to Actionscript 3 for all new development, I re-evaluated the debug class issue. I started work to port my uber-Debug class to AS3. I then realized that I never use the majority of the methods in the class. I mainly had traces at the top of key methods in my classes, and used the debug printer on occasion to figure out bugs in code. When the bug was gone, I removed the debug print to declutter the logs.
In the end, I realized that something complex that could do it all was not needed. The above function can be disabled for a single class by simply adding a return at the top of the function. More often than not I found myself needing debug for a particular class (say a PureMVC Mediator) only during some stages of development.
The moral of this story is that every once in a while we need to step back from the code editor, and look at the big picture to evaluate why we are doing something rather than focusing on the minutiae of what we are doing.