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()
?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With