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
2010-01-28 08:33:15
+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
2010-01-28 09:09:54
Awesome thanks.. using singleton is the way to go i think :)
Chris
2010-01-28 09:30:56
A:
You could use accessor and mutator class to set and retrieve the stage instance?
alvincrespo
2010-01-29 06:27:47