Last updated on: 2007-04-06
Version: 2.0

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

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:

[as]
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
}
}
}
[/as]

Example – Setting and getting dynamic variables:

[as]
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”);
}
}
}
[/as]

Example – Watching a variable:

[as]
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]);
}
}
}
[/as]

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)

58 Responses to “AS3 Global Object”

  1. Uza’s Blog & More » Blog Archive » AS3 Global Object 1.2 Says:

    [...] 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. [...]

  2. element Interactive » Tip: Fullscreen Stage [ as3 ] Says:

    [...] 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 [...]

  3. Uza’s Blog & More » Blog Archive » $.console - Flash Debugging Console Says:

    [...] it uses AS3 Global Object [...]

  4. Justin Windle Says:

    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.

  5. Mike Says:

    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.

  6. Chris Says:

    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?

  7. damian stewart Says:

    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.

  8. damian stewart Says:

    … 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.

  9. Ted Says:

    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()

  10. Joao Lopes Says:

    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!!!

  11. Rob Says:

    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

  12. AS3 Global Object « Soonthorn’s Weblog Says:

    [...] http://www.uza.lt/codex/as3-global-object [...]

  13. David Says:

    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.

  14. Globals in AS3 | flash cs Says:

    [...] Click here to find out more and download the class [...]

  15. Alexwebmaster Says:

    Hello webmaster
    I would like to share with you a link to your site
    write me here preonrelt@mail.ru

  16. 1985 » Global Variables in AS3 Says:

    [...] 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 [...]

  17. Joynisha Sumpter Says:

    Thanks David, that solved the issue for me as well.

  18. Lukasz 'Severiaan' Grela Says:

    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”);
    ??

  19. Clayton Says:

    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

  20. Five Life-saving tips for Flash developers « Archonic.com – Elegant | Effective Says:

    [...] 2. Uza’s Global Class [...]

  21. gnat Says:

    global.uza.Rocks();

  22. Bahaa Says:

    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 :(

  23. Yi’s blog - 优化fLEX程序性能的各种方法 Says:

    [...] 对于应用程序级别的事件,可以采用GlobalObject 或者 静态EventDispatcher 来做事件中转。这样设计的代价是增加了程序和这个程序级对象之间的紧偶尔,但是好处是大大降低了事件处理所需要的计算机资源。 [...]

  24. Five Life-saving tips for beginner Flash developers « Archonic.com – Elegant & Effective digital creations Says:

    [...] 2. Uza’s Global Class [...]

  25. Robert Penner Says:

    Global state makes me sad. Why promote this anti-pattern?

  26. Paulius Uza Says:

    @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!

  27. Zimbabalim Says:

    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!

  28. Chris Says:

    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?

  29. Globale variabler i ActionScript 3 · omFlash(); Says:

    [...] 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 [...]

  30. 如何彻底销毁一个类 | 傲天翔 の blog Says:

    [...] 对于应用程序级别的事件,可以采用GlobalObject 或者 静 态EventDispatcher 来做事件中转。这样设计的代价是增加了程序和这个程序级对象之间的紧偶尔,但是好处是大大降低了事件处理所需要的计算机资源。 [...]

  31. Martin Says:

    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.

  32. coderkind Says:

    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.

  33. Get Stage from a non-document class « Mobile Dev Blog Says:

    [...] will help that, Check out Uza’s Blog for AS3 Global [...]

  34. Danny Says:

    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.

  35. Paulius Uza Says:

    @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.

  36. Danny Says:

    @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.

  37. Paulius Uza Says:

    @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.

  38. jsin Says:

    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!!!!!!

  39. Plantar Fasiitis Shoes Says:

    Hmm it seems like your website ate my first comment (it was super long) so I guess I’ll just sum it up what I
    wrote and say, I’m thoroughly enjoying your blog.
    I as well am an aspiring blog blogger but I’m still new to
    the whole thing. Do you have any suggestions for
    beginner blog writers? I’d definitely appreciate it.

  40. калкулатор ипотечен кредит Says:

    Като цяло изключително бързо финансови заеми са невероятно високо цени .
    Ще намерите себе си се налага да плащат а годишно %
    цени че ще бъде няколко сто %
    . Като пример, може да заплащане на 20 лева процент
    до получите 100.00 лева за няколко месец .
    The купувач федерацията на България има някои хубави
    много добри изчисления
    оценка бързо Франчайз да опции .
    се установи, че може би изплати Проценти
    с Супер бързо ипотека , но
    плащат за споменатите по-горе % не е
    необичайно

    Feel free to visit my weblog – калкулатор ипотечен кредит

  41. dentist lees Summit Says:

    I am regular reader, how are you everybody? This paragraph posted at this website is really fastidious.

  42. Dacia Says:

    Hi there, I discovered your website by way of Google at the same time as searching for a
    comparable matter, your web site came up, it appears
    good. I have bookmarked it in my google bookmarks.
    Hi there, simply changed into alert to your blog thru Google, and located that it is truly informative.
    I’m gonna be careful for brussels. I’ll appreciate
    when you proceed this in future. Numerous folks will probably
    be benefited out of your writing. Cheers!

  43. Ashely Says:

    Howdy! I could have sworn I’ve visited this site before but after looking at many of the articles I realized it’s new to me.
    Regardless, I’m definitely pleased I discovered it
    and I’ll be bookmarking it and checking back frequently!

  44. skip hire price Says:

    I every time emailed this webloog post page to all my associates, because if like to read it
    after that my friends will too.

    my web site; skip hire price

  45. Seo Dunstable Says:

    Does your website have a contact page? I’m having
    a tough time locating it but, I’d like to sshoot you an email.
    I’ve got some recommendations for your blog you might be interested
    in hearing. Either way, great site and I look forward
    to seeing it grw over time.

    My site – Seo Dunstable

  46. how to fix garage door opener Says:

    I simply couldn’t depart your web site before suggesting that I actually enjoyed the standard info an individual supply to your guests?
    Is going to be again regularly in order to inspect new posts

    my page: how to fix garage door opener

  47. garage door repair Says:

    Cool blog! Is your theme custom made or did you download it from somewhere?
    A design like yours with a few simple tweeks would really make my blog jump out.
    Please let me know where you got your design. Cheers

    my page … garage door repair

  48. garage door repair Says:

    I’m not sure exactly why but this site is loading very slow for me.
    Is anyone else having this issue or is it a issue on my end?

    I’ll check back later on and see if the problem still exists.

    Here is my site – garage door repair

  49. genie blue max garage door opener Says:

    When I initially commented I clicked the “Notify me when new comments are added” checkbox and now
    each time a comment is added I get four emails with the same comment.
    Is there any way you can remove people from that service?

    Cheers!

    Feel free to surf to my web-site: genie blue max garage door opener

  50. garage door repair Says:

    Awesome! Its in fact awesome post, I have got
    much clear idea concerning from this post.

    my web site :: garage door repair

  51. craftsman garage door opener parts Says:

    You actually make it seem so easy with your presentation but I find this topic to be really something that I think
    I would never understand. It seems too complex and extremely broad for me.
    I am looking forward for your next post, I will try to get the hang of
    it!

    Feel free to visit my weblog craftsman garage door opener parts

  52. clepsydras Says:

    When someone writes an post he/she retains the image of a user in his/her brain that how a user can know it.
    Thus that’s why this piece of writing is outstdanding.
    Thanks!

    Check out my blog :: clepsydras

  53. トゥミ 財布 Says:

    It’s perfect time to make a few plans for the future and it’s time to be happy.

    I’ve learn this submit and if I may I wish to counsel you
    some interesting things or advice. Maybe you could write
    subsequent articles referring to this article.
    I want to read more issues approximately it!

  54. garage door repair Says:

    Do you have a spam issue on this blog; I also am a blogger, and I
    was curious about your situation; many of us
    have developed some nice methods and we are looking to exchange solutions with others, please shoot me an email if
    interested.

    Have a look at my web-site – garage door repair

  55. Resorts in europe booking Says:

    Hi there colleagues, how is everything, and what you would like to say
    about this paragraph, in my view its truly awesome designed for me.

  56. Susanna Says:

    All back with our Stellar Lifetime Warranty that’s transferable from builders to home-owners.
    The Sonic Alert is UL listed and comes with a five year manufacturer’s warranty.
    Some of these systems use remote cell phone door answering, which allows the user to unlock a door remotely using their cell phone as a trigger.

  57. Preston Says:

    IR night vision The door bell phone support IR
    night vision. The Sonic Alert is UL listed and comes with a
    five year manufacturer’s warranty. A mesh pocket on the exterior of the
    bed accommodates a tee shirt or shorts and provides optimal air circulation that allows the
    dog to easily detect the owner’s calming, familiar scent.

  58. James Says:

    Is he going to do his best to tear it apart and perhaps ingest part of it.
    Wireless alarm systems keep off the thieves and burglaries, making your home more secure
    when you are out. Pick a wireless doorbell here at great price & you can be assured of great quality too.

Leave a Reply