Monday, June 20, 2005

Flash: Constructing a Dynamic Function Call

Sometimes I don't know which function needs to be called until runtime. A good example is callback functions. If I have a function that takes the name of a callback function to execute I need a way to dynamically construct that call. Here's how:
theObject["theFunctionName"](param1,param2);
This is equivalent to:
theObject.theFunctionName(param1,param2);

Flash: Programming Asynchronously

Flash has a lot of built in asynchronous events, but there is no clear way to write your own code asynchronously. In Javascript a good way is to use the setTimeout(functionname,0) call to execute a method asynchronously. Unfortunately, Flash does not have setTimeout().

Luckily, a combination of setInterval(), clearInterval() and nested functions can be used to the same end.

In my particular application I am using the Observer design pattern for my event architecture. When an event method is called, it needs to execute asynchronously and then notify all registered observers when it is finished. Here's how I accomplished the asynchronous portion. This particular example echoes the argument back to the screen, asynchronously:
public function myEventFunction(param1:String):Void {
var interval = setInterval(asynchBlock,0,this);

/* All code you want to be asynchronous
* should go in this nested function
*/
function asynchBlock(parentObj) {
// Clear the interval so we never execute
// this block more than once.
clearInterval(interval);

// We can reference the original function params directly
trace(param1);

// We have to use parentObj to reference any variables
// declared outside of myEventFunction.
trace(parentObj.externalVariable);
}
}

Flash: Casting an Object to an Array

In Flash, it's impossible to cast an Object to an Array because of the existence of the global Array() function. Instead the Array has to be recreated manually:
var myArray:Array = new Array();

for(var i=0;i < myObj.length;i++) {
myArray[i] = myObj[i];
}