Static Stage and More…

Actionscript:
  1. package {
  2.     import flash.display.*;
  3.  
  4.     public class Main extends MovieClip{
  5.    
  6.         private static var _display:MovieClip;
  7.         private static var _stage:Stage;
  8.        
  9.         // use getters instead of public static vars so they
  10.         // cannot be reset outside of Main
  11.         public static function get display():MovieClip{
  12.             return _display;
  13.         }
  14.        
  15.         public static function get stage():Stage{
  16.             return _stage;
  17.         }
  18.        
  19.         public function Main(){
  20.            Main._display = this;
  21.            Main._stage = stage;
  22.            
  23.            // test out the static references
  24.            var t:Test = new Test();
  25.         }
  26.     }
  27. }
  28.  
  29. class Test{
  30.     public function Test(){
  31.         // test out the static references
  32.         with(Main.display.graphics){
  33.             lineStyle(1, 0xFF0000);
  34.             for (var i:int = 0; i<100; i++){
  35.                 lineTo(Math.random() * Main.stage.stageWidth,
  36.                        Math.random() * Main.stage.stageHeight);
  37.             }
  38.         }
  39.     }
  40. }

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:

Actionscript:
  1. 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....

This entry was posted in DisplayObject, OOP, variables and tagged , , . Bookmark the permalink. Post a comment or leave a trackback: Trackback URL.

Post a Comment

Your email is never published nor shared. Required fields are marked *

*
*