-
package {
-
import flash.display.*;
-
-
public class Main extends MovieClip{
-
-
private static var _display:MovieClip;
-
private static var _stage:Stage;
-
-
// use getters instead of public static vars so they
-
// cannot be reset outside of Main
-
public static function get display():MovieClip{
-
return _display;
-
}
-
-
public static function get stage():Stage{
-
return _stage;
-
}
-
-
public function Main(){
-
Main._display = this;
-
Main._stage = stage;
-
-
// test out the static references
-
var t:Test = new Test();
-
}
-
}
-
}
-
-
class Test{
-
public function Test(){
-
// test out the static references
-
with(Main.display.graphics){
-
lineStyle(1, 0xFF0000);
-
for (var i:int = 0; i<100; i++){
-
lineTo(Math.random() * Main.stage.stageWidth,
-
Math.random() * Main.stage.stageHeight);
-
}
-
}
-
}
-
}
This snippet creates two private static variables that reference the stage and the main timeline/document class. It then uses getters to regulate the use of these static vars so that they cannot be reset from outside the Main class.
Sometimes the amount of extra coding you need to do to maintain a valid stage reference can be cumbersome... similarly, passing references of the document class all around your app can be annoying. If you don't mind using two global vars in your app... this trick can come in handy.
What's nice about using getters here is that if someone tries to do this:
-
Main.display = new MovieClip();
they'll get an error... in flex, you even see that little red ex pop up next to this line of code if you write it ... that wouldn't happen with a public static var....