ActionScript Function Object – Know Who Called You!

I was working on what I thought would be a fairly simple solution, reusable code … which wound up biting me in the ass shortly after implementing it. I forgot to take into consideration that Alert.show() is non-blocking and so my reusable code that was turned into a function … failed to operate as I hoped it would. I came up with a really bad work-around which required the end user to perform the same action twice, now, last I checked … the definition of insanity was doing the same thing multiple times, expecting different results each time … so, I decided my ‘insane solution’ needed some work.

I looked around, thought it through and realized that ActionScript 3 (maybe even 2?) has a ‘Function’ object, which can basically store an instance of a function (most likely just a pointed to it, not a duplicate copy).

So, I had the following code:
[as]
private function canMove():Boolean { if(!isValid) {
Alert.show(“Your trying to move, but you cant … do you want too?”, “Can Not Move”, (Alert.YES | Alert.NO), this, function(event:CloseEvent):void {
if(event.details == Alert.YES) {
isValid = true;
}
});
return false;
}
return true;
}
private function doSomething():void {
if(canMove()) { /* do some more */ }
}

private function doAnotherThing():void {
if(canMove()) { /* do some more */ }
}
[/as]

Well, this code worked fine … but, as you can see … the user had to initiate the action of calling “doSomething” or “doAnotherThing” twice … once to make isValid true and once again to execute the ‘do some more’ code block. This was unacceptable. So I made the following changes:

[as]
private var lastAction:Function = null
private function canMove():Boolean { if(!isValid) {
Alert.show(“Your trying to move, but you cant … do you want too?”, “Can Not Move”, (Alert.YES | Alert.NO), this, function(event:CloseEvent):void {
if(event.details == Alert.YES) {
isValid = true;
if(lastAction != null) { lastAction(); }
}
});
return false;
}
return true;
}
private function doSomething():void {
lastAction = doSomething; if(canMove()) { /* do some more */ }
}

private function doAnotherThing():void {
lastAction = doAnotherThing; if(canMove()) { /* do some more */ }
}
[/as]

And viola, problem solved … ‘canMove’ would display an Alert and prompt the user, and the Alert’s callback could re-execute the code for them … perfect!

Leave a Reply