5
votes

I'm creating my first AS3 with FlashDevelop and I don't understand the meaning of the instructions in the constructor:

package 
{
    import flash.display.Sprite;
    import flash.events.Event;

    public class Main extends Sprite 
    {

        public function Main():void 
        {
            if (stage) init();
            else addEventListener(Event.ADDED_TO_STAGE, init);
        }

        private function init(e:Event = null):void 
        {
            removeEventListener(Event.ADDED_TO_STAGE, init);
            // entry point
        }

    }

}

What does if (stage) init(); mean? What is Event.ADDED_TO_STAGE? Why remove listener in init()?

1
I'm surprised not to see answers here yet, so while you're waiting: You get some interesting reading if you search for "Event.ADDED_TO_STAGE" which I suspect will answer your question. (I wouldn't know for sure, I don't work in ActionScript; that's why this isn't an answer. But the links look pretty on-target.) It looks to me like the aggregate effect is to ensure that init is called only when your component is on "stage": If you already are, you call it immediately. If you aren't, you hook up a listener for the event that fires when you're put on stage (and then remove it when it's called). - T.J. Crowder
Only one answer but a great one :) - user310291

1 Answers

9
votes

Main class is usually a document class -> class that is put to stage (root of display tree) as first. That means in constructor (Main function) you already have access to stage.

if(stage) init();

actually means that if stage != null, run initialization.

why test for null in document class?
If your swf get's wrapped into another swf. Your Main function will not have access to stage yet, because only sprites (movie clips, etc) that are on display tree (on stage) have access to stage.
Like this:

var mc:MovieClip = new MovieClip();//mc.stage == null
stage.addChild(mc);//mc.stage != null

So by adding a listener to ADDED_TO_STAGE you are waiting until you actually have access to stage, and then init it. You remove the listener right away because you don't need it anymore.

This is a common situation in document (main) class, because you need stage to add your menu, intro, whatever to stage, so it is visible.