Mike Chambers

code = joy

Global Variables within Flex Applications

with 23 comments

The question of how to set up global variables in a Flex application came up on the Flex Components list recently, and as it comes up every so often, I figured I would blog one of the answers.

This is actually very easy. Just define a public variable within your main application class, like so:

<?xml version="1.0" encoding="utf-8"?>
<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml" layout="absolute">
	<mx:Script>
		<![CDATA[
			public var foo:String = "bar";
		]]>
	</mx:Script>
</mx:Application>

You can then access that variable from anywhere within the Flex application via:

Application.application.foo

If you need to, you can still make the variable bindable.

Post and questions or suggestions in the comments.

Written by mikechambers

February 5th, 2007 at 4:31 pm

Posted in General

23 Responses to 'Global Variables within Flex Applications'

Subscribe to comments with RSS

  1. But how many situations are there where their use is really appropriate? Should we really be building applications that depend on global variables?

    That said, I can see some justification in terms of having access to the application environment and perhaps such things as login and security credentials, but I wonder how many use global variables at the expense of creating a maintainable application?

    I’d be interested in knowing good uses of global variables!

    Paul

    Paul Andrews

    5 Feb 07 at 4:57 pm

  2. Well, that is up to developer. However, as I have begun to work on Apollo applications and once again have more user defined settings (which must be persisted between sessions), I have found my self using this.

    I will sometimes store a settings class as a global variable and allow other parts of the application to bind to individual settings.

    I find this becomes more useful as my application becomes more complex, and keeps me from having to pass the settings class around to everything in my app that may need it.

    mike chambers

    mesh@adobe.com

    mike chambers

    5 Feb 07 at 5:02 pm

  3. Another thing you can do to create a global variable is create a singleton class, and refer to the variable instances within the singleton. Depends how you use it, but could be useful and cleaner in various scenarios, although it is definitely not as simple as what you mentioned above. For instance, your data model can be declared (similar to cairngorm) as:

    var model : ModelLocator = ModelLocator.getInstance();

    You can always access the model anywhere in your application, at any time using this method. An update to the model in one component would be an update to the “global” variable, and the change would be available throughout your entire application.

    Andrew Trice

    5 Feb 07 at 6:47 pm

  4. I’m surprised you don’t advocate using a singleton instead.

    Using Application.application.foo doesn’t give you compile time type safety unless you cast the application instance to the file name of your main app entry point. Casting to an application specific class makes the consuming component harder to maintain and use across multiple apps.

    I appreciate that Application.application.foo is simpler to understand, but in the long term it probably isn’t as robust as the singleton approach.

    Spike

    5 Feb 07 at 6:53 pm

  5. Hi mike,

    I think it may be not appropriate to call this as global variables as you can access any public or private variable or function (which is declared in the application) using Application.application.

    In my opinion Application.application will be something similar to _root in AS2 using which we can target the root of the application and call any thing which is declared on the root. In the case of flex application root will be the Application.application so using that you can access anything that is declared in Application.

    Global variable in AS2 has a special treatment; you have to specify _global to declare the global variable that can be called from anywhere form the application.

    Any Thoughts?

    ~ Suketu Vyas
    http://www.suketuvyas.com

    Suketu Vyas

    5 Feb 07 at 8:57 pm


  6. I think it may be not appropriate to call this as global variables as you can access any public or private variable or function (which is declared in the application) using Application.application.

    I dont necessarily agree with that. Regardless though, the question was how to access a variable gloabally from within the application.

    This example, as well as a Singleton example pointed out in the comments both address that.

    mike chambers

    mesh@adobe.com

    mike chambers

    5 Feb 07 at 11:03 pm

  7. Just starting with Flex and AS, could someone point me to a more complete example of using a singleton to hold vars.

    Thanks, Dave

    Dave

    6 Feb 07 at 7:05 am

  8. Dave, below is an example of a Singleton Class in it’s most basic form:

    package {
    public class Example {
    private static var instance:Example;

    public function Example(access:Access){
    if (access != null) {
    if (Example.instance == null){
    Example.instance = this;
    }
    }else {
    throw new Error(”Illegal operation”);
    }
    }

    //provides access to singleton instance
    public static function getInstance():Example{
    if (instance == null){
    instance = new Example();
    }
    return Example;
    }
    }
    }
    //restricts constructor access to private
    class Access {}

    Eric Feminella

    6 Feb 07 at 6:30 pm

  9. but you can access the global object too
    and declare it there then ;)

    package {

    import flash.display.Sprite;
    import flash.utils.trace ;

    public class MainClass extends Sprite
    {

    public function MainClass() {

    trace(”>> _global : ” + _global) ;
    trace(”>> myGlobalProperty : ” +
    _global.myGlobalProperty) ;
    }

    }

    }

    if (_global == null ) {
    var _global = this ;

    }

    you gotta love the internal namespace =)

    zwetan

    7 Feb 07 at 12:38 am

  10. I’d think singleton is appropriate for when you want a “global-like” class (and, naturally, only one instance) but not necessary for when you just want variables. In fact, I’d do something similar to this but rather keep the variable as a public var in a class accessible to all parts of your app. Usually, I’ll have one class Constants containing nothing but public static vars. From anywhere I access to set or get them using Constants.VAR_NAME. For all I know I’m doing this backwards but it has solved the use-case that _global used to provide.

    Phillip Kerman

    13 Feb 07 at 6:35 pm

  11. Reading the above comments with interest. Why store the vars in a Singleton that you need to instaciate.

    Could you not build a class that contains only static methods and pass the settings in via a static method. The class would then offer access to the settings via its static methods. There would then be no need for classes to ‘know’ about the instance, only the class.

    Simon

    20 Feb 07 at 10:12 am

  12. I realize that this will appear very rude, but I must say that I am shocked to see you Mike, a senior product manager at Adobe, give out tips on how to create global variables. I really hope that the developers on your team don’t take tips from you.

    I do apologize if I have misunderstood your intentions on this, and I do understand that this is a “feature” often asked for. But really, should you be promoting bad design?

    And to those of you suggesting singletons and monostates, while your intents are probably good too, the solutions you provide are no less global variables than Mike’s, they are just better disguised.

    A properly designed application does not need global variables, nor does it need singletons to provide global access to resources. That is not to say that the singleton pattern is bad, but it’s shouldn’t be used to solve the “problem” of lack of global variables.

    You can read more about proper use of the singleton pattern at the Portland Pattern Repository: http://c2.com/cgi-bin/wiki?SingletonPattern where there is also a discussion on global variables: http://c2.com/cgi-bin/wiki?GlobalVariable

    T#

    Theo

    7 Mar 07 at 12:51 pm

  13. That did come off a little rude. :D

    Anyways, you managed to shoot down the solutions mentioned, and that’s fine and all, but you didn’t actually suggest any solution of your own. What about things like environment variables or static paths or something? I’m just starting to look at Flex development, so I have no idea what the proper thing to do would be.

    Is there a fairly straightforward way that variables such as these could be defined in an XML file and accessed that way?

    Nick

    Nick Spacek

    18 Jun 07 at 5:36 am

  14. hot dang slick ! (theo) chill your schit out! punks like u are nothing special at all and don’t you ever ever think that you’re any smarter or “better” at programming than anyone else.. now ur just a dork that can read. its too bad you didn’t leave a website we could all exploit and kick u out the club.

    punk.

    my name is jonas

    jt

    6 Nov 07 at 6:18 pm

  15. I am about three weeks into flex and actionscript and I’m a big dummy. I just wanted to throw in a quick note for people who may not have noticed this like me:

    You can’t just refer to a variable from your application with:

    Application.application.blah_blah

    You first either have to import the Application component:

    import mx.core.Application;

    Application.application.blah_blah;

    or reference it directly:

    mx.core.Application.application.blah_blah;

    Atleast that’s what’s working for me now!

    Alan

    29 Nov 07 at 7:34 pm

  16. This is refers to the Theo comment. Rude or otherwise, its important for Theo to understand that for the first rung developers like me with huge delivery pressures, quick fix solutions are a very must. (Please dont give me that this hurts in long run etc. I know it well. It earns money for the non-programmer trainer). And i think Mike is super cool as he cares for the programmers like us by sharing such tips despite being in a position where does not need to do so. Thanks Mike. You rock!

    Prath

    3 Dec 07 at 3:14 am

  17. Is it possible to bind to a Singleton?

    Bo Bartlett

    3 Jan 08 at 6:31 am

  18. I can reference these variables, but I can’t seem to bind to them. When I do, I get the infamous:

    warning: unable to bind to property ‘application’ on class ‘mx.core::Application’ (class is not an IEventDispatcher)

    But I can reference these in components and elsewhere and get the values of them. Can you not bind to the Application class?

    _t

    30 Jan 08 at 1:27 pm

  19. I would have to agree that Application.application is very rarely the best way of creating “global” variables. Sure, in some cases it’s okay, but make sure you learn this lesson:

    NEVER bind to variables using Application.application

    In my experience, it will create a memory leak in nearly all cases. If you must bind, use a singleton. I believe the best way to implement a singleton is the way it’s done in Cairngorm (I hate Cairngorm, but at least they do this one thing well).

    I respect Mike, and I will grant that in some cases creating global variables using “Application.application” is acceptable (although I personally try to avoid it), but I think Mike probably should have given a little more caution in his blog post so as not to mislead developers who are new to Flex.

    Jake Hawkes

    11 Feb 08 at 12:46 pm

  20. @Jake

    Sorry, but on this one you’re quite wrong. There is a very common Flex scenario where using Singleton’s just doesn’t work, but Application.application does. Singleton’s don’t work when you build a modular system, where each module is its own swf, and loaded using SWFLoader or ModuleLoader. However, with such a modular system works great with globals loaded from Application.application. I use Application.application frequently, and have never encountered mem leaks like you describe.

    The use of Singletons is the primary reason that Cairngorm doesn’t work with modular Flex apps. That and the problem of multiple instance of commands loaded into controllers causing things to double/triple/etc load.

    Dan Martin

    7 Mar 08 at 1:10 pm

  21. jari,

    several ways:

    .outerDocument

    .parentDocument

    if you have an id of the element just use the element.id.

  22. As far as globals goes… (at least from an old school C++ programmer)

    It is always best practice to contain the data in the class designed specifically for that class.

    With that said, there are always reasons to do global variables…

    For instance, I have my components set up to display different tools depending on the access of the user (Set through a remote object component). There may be an edit button if the person has edit rights for instance.

    I have a global user object that each of the components can easily refer to. I also have a bind set so that the components can react if a variable changes (like if the user logs out).

    I could be wrong on this… But I don’t see another way to easily get around that by keeping the information in the login component.

    This is only one example, I can think of numerous ones that I’ve encountered over the past 30 years of coding.

    However with that said you should ALWAYS ask yourself, is this the best place to store the variables? What and how do other pieces of code have to do to access them? It’s never best practice to store 95% of data in public variables (unless you’re doing BASIC code that is… ;)

    Scott

    15 Jul 08 at 7:28 am

  23. I just tried what
    mikechambers said on February 5th, 2007
    and
    Alan said on 29 Nov 2007 at 7:34 pm.

    It worked for me.

    I was trying to get the values of 2 variables created for use in one mxml state file to be available in another one so that I could post them to a server. The two files are in the same package. The main application mxml imports the package they are in.

    I would like to know a better way than what I have done. If there is one.

    George

    giechika

    29 Aug 08 at 2:04 am

Leave a Reply