Timmy
Timmy

Reputation: 12848

Proper way to dispatch/handle message in actionscript 3?

I have a constructor in a class that does some kind of logic:

public function Constructor() {
   if some condition {
      // load some resource from the internet, dispatch message when done
   }
   else {
      // finish up, dispatch message now
      dispatchEvent( new TestEvent( ... ) );
   }
}

and a class that uses this:

obj = new Constructor();
obj.addEventListener( ... );  // Listens to the above event

I am running into trouble because if "some condition" does not happen, it immediately dispatches the event, but the second class will not hear the event because it executes before the addEventListener method.

Upvotes: 1

Views: 127

Answers (1)

spender
spender

Reputation: 120508

Simple. Do not fire events in a constructor. Construct the object, hang your listeners then call an initialization method that contains the event firing code.

EDIT: Alternatively, if you absolutely must, pass in the a callback method as a param to the constructor, and add the listener in the constructor.

I prefer the former method, as it is less obfuscated.

Upvotes: 2

Related Questions