views:

134

answers:

3

How do I access the stage in Actionscript 3 in a class which is not my main class and not a displayobject?

A: 

The easy way, you can keep it in a static var for example:

public class MyMain extends Sprite {
 public static var STAGE:Stage;

 public function MyMain() {
  if (stage)
   init();
  else
   addEventListener(Event.ADDED_TO_STAGE, init, false, 0, true);
  }
 }

 private function init(e:Event=null):void{
  removeEventListener(Event.ADDED_TO_STAGE, init);
  // store stage reference when stage ready  
  STAGE=stage;
 }
}

and in your other class import the class that is holding the static var, of course the var have to be initialized before accessing it.

import MyMain;

public class Other {
 public function useStage():void {
   MyMain.STAGE...
 }
}
Patrick
+1  A: 

the easiest way is to use a global object

http://github.com/inruntime/AS3-Global-Object

this page has examples of how to set and retrieve objects from any class.

Josh
Awesome thanks.. using singleton is the way to go i think :)
Chris
A: 

You could use accessor and mutator class to set and retrieve the stage instance?

alvincrespo