views:

27

answers:

1

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.

+2  A: 

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.

spender
So simple/stupid. Thanks!
Timmy