views:

46

answers:

2

I need to return to my original function after capturing an event (downloading something) with another function. The original function needs to return a value, which depends on the downloaded data. So, I'd like to pause original function for the time needed for the download and the eventhandler function to complete it's work, and resume it afterwards.

The obvious way is to set a flag value (both the original function and the eventhandler are within the same class) and make the original function check it until the eventhandler function changes the flag. But that would be wasteful, and my AS is slow enough already:) [other parts of the application utilise some heavy graphics].

Is there another way? Like an event that gets captured "in the middle" of the function? Or some other form of flow control?

+2  A: 

You'll need to split the function that's waiting for the event handler into a callback that resumes the rest of your code after your event has fired:

public function non_blocking():void {
   // code that needs to run before the event here]

   var callback:Function = function(e:Event):void {
      // test return type here
      // ... continue with the rest of your code
   };   

   addEventListener(YOUR_EVENT_TYPE, callback);
}
jdeseno
The trouble is, I need the non_blocking() function to return something, and that depends on the callback. The non_blocking is part of an external interface for the object, and other classes calling it need a return to know whether the object is valid (it is sort of a loading function to be called after the constructor. If it returns true, the object holds data, if not, it should not be used.) But if the externally-called function terminates, the callback has no (known to me) way to talk to the external class that called... other than launching another event, but that would mangle my design.
J.Ded.
Hmmm... on the other hand, launching another event is how URLLoader works, and it does work:). Maybe the changes wouldn't be that drastic... Meanwhile, is there another way?
J.Ded.
jdeseno
Yes. That's what I'm looking for. But I can't seem to find even a decent "wait" that doesn't launch a whole new function (like Timer, onTimerEvent):)
J.Ded.
A: 

It doesn't work like this. You can't have code just sitting there waiting for something else to finish, Actionscript execution is single threaded only. You need to do as suggested by jdeseno, split it up into multiple functions.

davr
That's my definite answer, although not one I was hoping for:). Already did the splitting, it's a little more coding (new Event subclass and a few changes in dependencies) but it works. Still getting used to AS3. Thanks both to you and j.deseno.
J.Ded.