How to access the stage from an AS3 class in Adobe Flash

actionscript-3classflashkeyboardstage

The problem I've encountered is that I am using a keyboardEventListener to make a movieclip run around. As I'm a college student, I'm creating this for an assignment but we are forced to use as3 classes.

When I run the code in the maintimeline, there is no problem. But when I try to access it from another class (with an 'Export for ActionScript' on the movieclip in question) I get an error he can't address the stage.

this.stage.addEventListener(KeyboardEvent.KEY_DOWN, dostuff);

Best Answer

A class in AS3 is not on the stage until you actually place it there. As a result, "this.stage" will be null at compile time. You can get around this problem by using the ADDED_TO_STAGE event to delay binding your listeners until the time is right.

public function MyClass(){
    this.addEventListener(Event.ADDED_TO_STAGE, addedToStageHandler);
}

private function addedToStageHandler(e:Event):void{
    this.stage.addEventListener(KeyboardEvent.KEY_DOWN, dostuff);
}
Related Topic