Question

I often have problems with my code if I don't have the following in my constructor:

addEventListener(Event.ADDED_TO_STAGE, init, false, 0, true);

Once I execute code after my MovieClip or Document Class has been added to stage, it seems to work better...but why is this?

Was it helpful?

Solution

Think of it this way: if your class is being constructed, it MIGHT be from some hosting code that looks something like this:

var newComponent = new TheComponent();
parentElement.addChild(newComponent)

So, if you are executing code in the constructor, you are executing code that is not fully wired up yet. For instance, you will never have a parent in your constructor because you haven't been added to the hierarchy yet.

Of course, some things will work... any code that does not rely on being part of the visual tree, for instance, will work. BUT, any code that relies on knowing that is part of a bigger system will need to execute AFTER it is added to the stage.

Does that help?

OTHER TIPS

Adding onto Brian's explanation, ADDED_TO_STAGE is there to make management of an object within a single class easier. By allowing the object to know when it's added and removed from that stage, you have have it manage it's self entirely. Say, starting an animation in the handler method or stopping it when removed. Normally without that event you would have to have the object adding it to the stage start and stop.

Think of the event framework as an automation framework that called methods/functions whenever a particular event is broadcasted. Because the ADDED_TO_STAGE is dispatched on and object in the addChild method, it's similar as to calling a custom method bind().

package{
 class Main extends Sprite{
  public Main(){
   // called on instantiation.
  }
  public function bind():void{
   //called later in the stack, either by ADDED_TO_STAGE or main.bind()
  }
 }
}

It's because those properties ( x,y,alpha ) are being initialized in the addChild method. This is done for memory management reasons. Why allocate a few bites for something that will not be processed until the object 'hits' the stage.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top