AS3 Global Object
General:
Global Object is a Singleton that lets you store dynamic variables in a globally accessible location within your AS3 application. This enables developers to accomplish things like self registering visual components, global events and event listeners.
Requirements:
Actionscript 3
What's new in v2.0
- Refactored code and class locations
- Package changed from lt.uza.utils to com.inruntime.utils
- Project now has a home at GitHub - http://github.com/inruntime/AS3-Global-Object
What's new in v1.2:
- Added - Global fires an Event every time a property is updated (you are now able to watch variables).
- Added - GlobalEvent class
- Added - global.take(s:*):* function, similar functionality to global[s];
Example - Initializing the Global Object:
Actionscript:
-
package {
-
import flash.display.*;
-
import com.inruntime.utils.*;
-
public class Test extends Sprite
-
{
-
// initialize the global object
-
// you have to repeat this step in every class that will use the global
-
private var global:Global = Global.getInstance();
-
-
public function Test(){
-
// your application code here
-
}
-
}
-
}
Example - Setting and getting dynamic variables:
Actionscript:
-
package {
-
-
import flash.display.*;
-
import com.inruntime.utils.*;
-
-
public class Test extends Sprite
-
{
-
private var global:Global = Global.getInstance();
-
private var testSprite:Sprite = new Sprite();
-
-
public function Test(){
-
//setting variables is easy, global object accepts any name / value pair, even functions
-
global.stage = this.stage;
-
global.testA = "a"
-
global.testB = testSprite;
-
global.testF = test;
-
-
//getting variables is easy too
-
trace(global.testA);
-
this.addChild(testB);
-
-
//as easy as calling a globally stored function
-
global.testF();
-
}
-
-
private function test():void {
-
trace("this is a global test");
-
}
-
}
-
}
Example - Watching a variable:
Actionscript:
-
package {
-
import flash.display.Sprite;
-
import com.inruntime.utils.Global;
-
import com.inruntime.utils.GlobalEvent;
-
-
public class test extends Sprite
-
{
-
private var global:Global = Global.getInstance();
-
-
public function test()
-
{
-
global.addEventListener(GlobalEvent.PROPERTY_CHANGED,onPropChanged);
-
-
// Event fires when you set or update a direct property of Global storage
-
global.variableA = 1;
-
global.variableA = 23;
-
global.variableA = 41;
-
global.variableB = 20;
-
global.variableB = global.variableA;
-
-
var sp:Sprite = new Sprite();
-
global.sp = sp;
-
-
// Event does not fire when you set a property of an object inside Global storage.
-
global.sp.x = 10;
-
global.sp.x = 23;
-
sp.x = 34;
-
}
-
-
private function onPropChanged(e:GlobalEvent):void {
-
// Property name can be accessed through GlobalEvent object;
-
trace ("property "+ e.property + " has changed to " + global[e.property]);
-
}
-
}
-
}
Acknowledgments
Anthony Sparks for pointing me out to some web hosts that offer free domain hosting.
The Global Object has been built on top of HashMap class by Eric Feminella
Latest version
Download link (6Kb)


May 11th, 2007 at 1:28 am
[...] AS3 Global Object has been updated with several new features, the most important of them is an ability to watch a property. Global fires an event every time a property is created or updated. [...]
August 3rd, 2007 at 7:52 am
[...] one of my favorite class packages around is Uza's AS3 Global Object I Use it in this example and it is included with the download. You can do much more with it that i [...]
August 25th, 2007 at 4:22 am
[...] it uses AS3 Global Object [...]
September 13th, 2007 at 7:29 pm
Good work! I have seen a lot of people struggling with the loss of _global on various forums. I had developed an inferior version of this as a result, but I will switch to yours. Great touch with the events too.
Thank you.
September 14th, 2007 at 9:58 pm
I am having a problem getting the globals to work. When I try to create a new global var with "var global:Global = Global.getInstance();" I get this: TypeError: Error #1009: Cannot access a property or method of a null object reference. at com.lt.uza.utils::Global/http://www.adobe.com/2006/actionscript/flash/proxy::setProperty()
at Main/::frame1()
I went in and added the "com." to all included files. I have nothing in the files other than creating a var and attempting to trace it.
June 6th, 2008 at 5:48 pm
What's the deal with typed variables? I mean, I'm forced to write this:
global.x = 20;
instead of:
global.x:int = 20;
is this done within the class?
July 31st, 2008 at 3:48 pm
hey, just a heads-up re AS3's 'static' keyword. i'm not sure whether this is a bug or a deliberate design decision, but the 'static'ness of a variable does not propagate up the document tree to the root.
in short, what this means is that you have to construct your Global singleton instance within the DocumentClass of the root document. if you don't do this - if you let it be constructed lazily as necessary by some kind of child movie clip - it will be 'global' to that child movie clip and its children.
let me give an example. suppose you have a document class MyDocumentClass that loads as two children movie_a.swf and movie_b.swf. suppose also you have class MultiLangManager, with a static function GetInstance() that fetches the static singleton instance, constructing a new one if necessary. like this:
class MultiLangManager() {private static var instance:MultiLangManager = null;
public static function GetInstance() : MultiLangManager() {
if ( ! instance ) {
trace("constructing singleton instance");
instance = new MultiLangManager();
}
return instance;
}
}
now, at some point movie_a.swf calls MultiLangManager.GetInstance(). MultiLangManager goes ahead and constructs the singleton. sometime later, movie_b.swf calls MultiLangManager.GetInstance(). you'd MultiLangManager to return the existing instance. it is static, after all, right? wrong. what you get is *another* singleton, that is also static, but only 'locally' static. you know this, because the console says "constructing singleton instance" not once, but twice.
thanks Adobe. you suck. when on earth this could be useful, i have absolutely no idea.
the way around this is, if you add to the MyDocumentClass constructer, the line
MultiLangManager.GetInstance()it will construct a properly singleton properly static instance that is then visible by both movie_a.swf and movie_b.swf.
which means, of course, that MyDocumentClass has to know which static instance both movie_a.swf and movie_b.swf are going to access. considering the fact that 'static' is supposed to be an elegant work-around to the problem of sharing data between instances without requiring some tight coupling in the middle, Adobe's implementation is somewhat broken, to say the least, since it brings the coupling issue right back to the foreground.
July 31st, 2008 at 3:51 pm
... if you let it be constructed lazily as necessary by some kind of child movie clip - it will be 'global' to that child movie clip and its children...
should be -
if you let it be constructed lazily as necessary by some kind of swf loaded as a child - it will be 'global' to that child swf (say child.swf) and its children _only_. attempts to access it from a sibling of child.swf, or from the parent, will result in a new instance being created.
September 16th, 2008 at 9:53 pm
Why do I get this error when I try to set a variable????
TypeError: Error #1009: Cannot access a property or method of a null object reference.
at utils::Global/http://www.adobe.com/2006/actionscript/flash/proxy::setProperty()
at Main()
November 15th, 2008 at 6:00 am
I've a big problem to solve! Since i'm a graphic designer my code experience is very limited. However I created a class that do some stuff and than I need to send back to the timeline some variables. The problem is that i cannot use the return function since the maths and other stuffs are stucked into private functions.
I've tried the dispach event but withour results. It's possible to create a global variable into the function and a listener, looking for changes on this variable, in the timeline? Please help me!!!
November 17th, 2008 at 3:45 pm
Hello,
These classes seems to be very good. However, I'm limited regarding actionscript.
This is my problem:
I've downloaded the folders into where my project are. I have created a class that uses the example code that you find on the homepage.
Then I call to that class from my project. Unfortunately that doesnt work.
So my project calls on the class that I have created from the example code and that class calls on the classes in the \lt\uza\utils folder...
please help me
best regards
rob
December 19th, 2008 at 4:25 pm
[...] http://www.uza.lt/codex/as3-global-object [...]
January 15th, 2009 at 7:50 pm
To Mike who was getting the TypeError: Error #1009 after adding "com." to included files -- in Global.as you need to add "com." here:
public function Global()
{
if (getQualifiedClassName(super) == "plugins.lt.uza.utils::Global" ) //etc
This solved the same problem for me.
January 22nd, 2009 at 2:12 pm
[...] Click here to find out more and download the class [...]
March 3rd, 2009 at 1:56 pm
Hello webmaster
I would like to share with you a link to your site
write me here preonrelt@mail.ru
March 17th, 2009 at 11:46 am
[...] anyone is looking for a more robust global variable solution, i highly recommend looking at uza’s GlobalObject class. It uses a nice hash map and dictionary to track the variables and dispatches events when [...]
May 30th, 2009 at 4:39 pm
Thanks David, that solved the issue for me as well.
June 4th, 2009 at 1:03 pm
Hi Paulius,
this is one very usefull class:) but how to remove global references, I can not use delete which would be usefull, remove doesn't say much to me, is the name paramtere the name of the global variable?
i.e. global.engine = this;
global.remove("engine");
??
July 9th, 2009 at 12:45 am
Lukasz, I actually had the same question. I was wondering about cleanup, of all my variables.
For now, i'll set everything to "null" but wonder if it can be deleted/removed.
Thanks,
C
July 15th, 2009 at 9:32 pm
[...] 2. Uza’s Global Class [...]
July 23rd, 2009 at 3:18 pm
global.uza.Rocks();
July 31st, 2009 at 4:20 pm
i have downloaded the file and created the class as in your example, butam trying to create a global array, and i need to use it in other parts in my file
i keed getting this error
1120: Access of undefined property global.
Please Help
September 26th, 2009 at 12:47 pm
[...] 对于应用程序级别的事件,可以采用GlobalObject 或者 静态EventDispatcher 来做事件中转。这样设计的代价是增加了程序和这个程序级对象之间的紧偶尔,但是好处是大大降低了事件处理所需要的计算机资源。 [...]
October 27th, 2009 at 8:10 pm
[...] 2. Uza’s Global Class [...]
November 11th, 2009 at 1:27 am
Global state makes me sad. Why promote this anti-pattern?
November 11th, 2009 at 1:42 am
@Robert Penner
Thanks for dropping by!
Although I admit that global variables CAN cause problems, many programs can benefit from them if used in a controlled manner. I'm using development patterns myself everyday, however I find Global class a great addition to my toolset letting me create difficult systems with less code and clutter.
Another reason is that if you are doing real life development on a tight budget and an even tighter timeline (thus cannot invest time in using propper MVC), Global will most probably be your best solution to get things done fast and clean.
OOP strongly opposes any global variables, however I believe my AS3 implementation is quite compatible to pass the check.
Give it a try!
December 10th, 2009 at 4:35 am
Great for me! I'm creating a bi-lingual webshop in Flex that needs to update the text in everything on the fly including the contents of query driven xml category and item views. Really didn't want to create a chain of public references all the way along these paths. This has really saved me time and clutter by passing along 'currentLanguage' from the bottom of the stack. Effectively just bubbling an event from the bottom - nice one!
December 30th, 2009 at 4:41 am
Thanks heaps, I really enjoy this handy tool. In your Watching a variable example how do I setup a listener for just one var?
Example global.test.addEventListener(GlobalEvent.PROPERTY_CHANGED,onPropChanged); I just want to listen to the test var without setting up different case if statement in the onPropChanged function. Or is this not what you intended for?
July 31st, 2010 at 2:38 pm
[...] du er i humør til at være doven, så kan du jo overveje at smutte herhen og læse mere om den: AS3 Global Object Tags: as3, global Del:These icons link to social bookmarking sites where readers can share and [...]
August 22nd, 2010 at 1:06 pm
[...] 对于应用程序级别的事件,可以采用GlobalObject 或者 静 态EventDispatcher 来做事件中转。这样设计的代价是增加了程序和这个程序级对象之间的紧偶尔,但是好处是大大降低了事件处理所需要的计算机资源。 [...]
September 13th, 2010 at 11:41 am
Hallo, I really like your Global Class. While watching a Porperty wouldn't it be nice to have the old Value also beeing returned in the GlobalEvent? That way I could easily compare old and new for further action. Like this:
override flash_proxy function setProperty(name:*, value:*):void {
var data:Object = new Object;
data.name = name;
var oldValue:* = globalRepository.getValue(name);
if(!oldValue) {
globalKeychain.put(name,globalIncrement.toString());
globalIncrement++;
}
globalRepository.put(name , value);
data.oldValue = oldValue;
data.newValue = value;
if(oldValue !== value) {
dispatchEvent(new GlobalEvent(GlobalEvent.PROPERTY_CHANGED,name));
dispatchEvent(new GlobalEvent(GlobalEvent.PROPERTY_CHANGED_VALUE,data));
}
}
Thanks a lot.
March 23rd, 2011 at 7:55 pm
How would you manage this if the Global class was exported as a .swf and loaded in at runtime? I’m having problems working out how to reference the instance once Event.COMPLETE has fired from the Loader instance used to bring in the .swf.
June 4th, 2011 at 6:36 am
[...] will help that, Check out Uza’s Blog for AS3 Global [...]
June 23rd, 2011 at 12:29 am
This project may be long dead, but any response will be highly appreciated.
So I was curious what this does as far as garbage collection, and if i need to set my $ variables to null in my child.swf's
For example;
parent.swf does: private var $:Global = Global.getInstance();
Then in my child.swf, I also do:
$:Global = Global.getInstance();
so that it can access the variables in $. Just boolean type variables, not storing any references to any movieclips or listeners. Things that would normally be collected in garbage collection.
So then when I remove child.swf should I also be calling $ = null in child.swf to make sure its not "hanging on" to the $ global? Or will calling $ = null in my child make $ null everywhere?
In theory I would think, no, i dont need to set $ = null, but this "global" stuff gets a bit confusing as to what makes things stick in memory.
June 23rd, 2011 at 1:00 am
@Danny
The project is far from being dead - to my knowledge it's used in production in hundreds of new projects every month.
Since Global.getInstance() is a singleton pattern, it creates only one instance of the class, so each $ is just a reference.
if you want to unset a specific globally stored variable, you would call $.variable = null
this will mark $.variable to be garbage collected on the next GC run
if you want to garbage collect the $ object, you would have to unset it everywhere that it was initialized by doing $ = null; However, this is an extreme case and I have not seen a case where this would be necessary.
June 23rd, 2011 at 3:23 am
@Paulius Uza
Thanks for the response, and no offense by questioning if the project was dead. I couldn't tell by the dates people last posted. So far it is the best solution to a Global that I have seen around.
Just so I am completely clear; If I call $:Global = Global.getInstance(); in my child.swf, I do NOT have to call $ = null in order for my child.swf to be eligible for garbage collection?
My only thought is that I am creating a variable named $ in my child, and I don't want my child to remain in memory just because its hanging onto that instance.
June 23rd, 2011 at 12:01 pm
@Danny thanks.
AFAIK it should not stop GC from doing it's job. Setting your child swf variable to null and detaching it from stage should be enough.
August 27th, 2011 at 2:22 am
In example 2 I think you forgot to put global before the second testB:
this.addChild(testB);
should be:
this.addChild(global.testB);
at least it wouldn't work for me until I made that change.
GREAT CLASS!!!!!!! THANK YOU!!!!!!