AS3 Cannot access stage from custom class

actionscript-3spritestage

How can I access the stage and especially the width and mouse position of the flash Movie from a custom class?

package classes
{
   import flash.events.*;
   import flash.display.*;

   public class TableManager extends Sprite
   {
        public function TableManager() {
            sayStage();
        }
        public function sayStage():void 
        {
            trace(stage);
        }
  }   
} 

This will only return nill. I know that DisplayObjects don't have any stage until they have been initiated so you can't access the stage in your constructor but even if I call sayStage() later as an instance method it won't work.

What am I doing wrong?

Best Answer

If TableManager is on the stage you can access the stage with this.stage.

The trick is you have to wait for the instance to be added to the stage. You can listen for the ADDED_TO_STAGE event so you know when that's happened.

package classes {
import flash.events.*;
import flash.display.*;

public class TableManager extends Sprite {
    public function TableManager() {
        this.addEventListener(Event.ADDED_TO_STAGE, onAddedToStage);
    }

    private function onAddedToStage(e:Event):void {
        this.removeEventListener(Event.ADDED_TO_STAGE, onAddedToStage);
        sayStage();
    }

    public function sayStage():void {
        trace(this.stage);
    }
}   
}
Related Topic