Search code examples
actionscript-3stage

Why Event.ADDED_TO_STAGE


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?


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?