Async APIs and Anonymous Functions

ActionScript has a nifty feature called anonymous functions that is often handy when working with asynchronous APIs. Here’s how it works:

var t:Timer = new Timer( 0 );
var message:String = “Hello, World!”;
t.addEventListener( TimerEvent.TIMER_COMPLETE, function( evt:Event ):void { trace( message ); });

Here, function creates a new, anonymous function taking one argument (an event) and with the body specified inline. I don’t recommend using this technique for long event handler functions; those are usually easier to write as callback functions. But this is a great technique to use when your callback function is short. Replacing a whole set of short callback functions with anonymous functions is a great code cleanup.

Note in the example above that the function body is able to reference message, which is a variable that was defined back in the code that created this function. Creating an anonymous function creates a closure that captures the in-scope variables visible where the function is defined and makes them available when the function executes. This saves you the trouble of littering your class with member variables that exist just to remember stuff until an event handler gets called. Another great code cleanup.

This wraps it up for the basic techniques for asynchronous programming. Next we’ll start in on more advanced topics.