Symmetri Developer Blog

February 6, 2008

Simulated globals in Actionscript 3

Flash/Flex - By Shourov Bhattacharya

I have never really understood the argument against global variables. Yes, they can be used in sloppy ways by sloppy programmers, in which case they do contribute to making code difficult to read and maintain. But to banish them altogether seems to me to be an ideological stance rather than one driven by logic. A global variable is an absolute point of reference within the world of the application, as opposed to the “relativism”of class members and properties. There are solid reasons for sometimes wanting to have an absolute reference.

An example is the main stage of a Flash application. There is only one stage, and there may be display objects on that stage that need to be referenced from different parts of the application. Flash CS3 and Actionscript 3 have taken the ideological stance and eliminated both the _root and _global objects, so that it is no longer possible to reference instances of MovieClips (for example), using the following code:

var myClip:MovieClip = _root.clip01;

Likewise, using _global in the same way no longer works in AS3.

So , how can we reference “global” objects in AS3? We do still have the DisplayObject.root property, which refers to the root of the display tree that contains a display object. And we do, of course, have static classes, which can hold static variables of any type. Combining these two, we now have a strategy to “simulate” the _root object reference:

1) Create a static Application class to hold globals
2) When instantiating one particular DisplayObject in the application, assign its root property (which will be the main stage) to a static variable _root on the Application class
3) use Application._root from anywhere in the application to refer to the main stage

Here is the stub for the Application class:

public class Application
{
   static public var _root:DisplayObject;
}

and an example of how to assign to the _root property (assume here that Clip is the class for a MovieClip instance that is added at design time to the stage):

public class Clip extends flash.display.MovieClip
{
   public function Clip()
    {
      Application._root = this.root;
   }
}

A similar approach can be taken to store any object in the Application class as a “global” variable. You could even write a generic class wrapper that would allow you to “push” and “pop” global variables easily from an array or other data structure (I am sure this has already been done somewhere).

Get free blog up and running in minutes with Blogsome
Theme designed by Janis Joseph