ActionScript Function Object - Know Who Called You!

Posted in: ActionScript |

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:

Actionscript:
  1. private function canMove():Boolean {   if(!isValid) {
  2.      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 {
  3.        if(event.details == Alert.YES) {
  4.          isValid = true;
  5.        }
  6.      });
  7.      return false;
  8.    }
  9.    return true;
  10.  }
  11.  private function doSomething():void  {
  12.    if(canMove()) { /* do some more */ }
  13.  } 
  14.  
  15.  private function doAnotherThing():void {
  16.    if(canMove()) { /* do some more */ }
  17.  }

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:

Actionscript:
  1. private var lastAction:Function = null
  2.   private function canMove():Boolean {   if(!isValid) {
  3.      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 {
  4.        if(event.details == Alert.YES) {
  5.          isValid = true;
  6.          if(lastAction != null) { lastAction(); }
  7.        }
  8.      });
  9.      return false;
  10.    }
  11.    return true;
  12.  }
  13.  private function doSomething():void  {
  14.    lastAction = doSomething;   if(canMove()) { /* do some more */ }
  15.  } 
  16.  
  17.  private function doAnotherThing():void {
  18.    lastAction = doAnotherThing;   if(canMove()) { /* do some more */ }
  19.  }

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!

Want to Advertise on this Site?