Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What does "if (stage) init();" mean in ActionScript?

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()?

like image 690
user310291 Avatar asked Jun 06 '10 21:06

user310291


1 Answers

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.

like image 135
Antriel Avatar answered Sep 28 '22 11:09

Antriel