Get Access to the Stage Wherever You Need It

Written by Mike Creighton on December 21st, 2008

In ActionScript 2, it was possible to access the stage from anywhere, through the static Stage class. With ActionScript 3, we lost that ability, and only display objects were permitted access—and only once they had been added to the stage.

To help you get access wherever you need it, CASA Lib for AS3 has a utility class called StageReference in the org.casalib.util package. It’s a static class that lets you keep track of the stage (or multiple stages if you’re developing an AIR app with multiple windows). Here’s how we recommend using it.

In the constructor of your main document class, just call this line of code:

StageReference.setStage(this.stage);

Now, throughout your entire site or application, you can get access to the stage reference from anywhere by using this line of code:

StageReference.getStage();

Take a look at the class’s documentation to see what else the StageReference class can do. Some classes (like CASA Lib’s Key class) require the use of the StageReference class to function properly.

Comments

Written by Taylor Wright on January 27th, 2009

Thanks for posting this tutorial, I’d otherwise missed the class in the docs. This feature has been so useful for me, it’s nice to get rid of or pair down on a lot of ADDED_TO_STAGE events that otherwise felt excessive.

Written by Sean on February 13th, 2009

Great class, this solves some of the frustrations I’ve been having over the last few weeks.  Thanks so much.

Written by awariat on January 7th, 2010

works very nice. it is possible to add own variable to stage and get it in the same way like in your example(stageWidth)

Written by Aaron Clinger on January 7th, 2010

Awariat, you can get the stageWidth like so: StageReference.getStage().stageWidth

Written by Mike Creighton on January 7th, 2010

Also awariat, if you’re asking if you can declare your own custom variables on the StageReference.getStage() object, that’s not possible. It’s still a Stage object, and isn’t a dynamic class.

Comments are no longer accepted for this blog post.