Hello. I have a new blog.

I've moved this blog to the following URL Kerkness.ca. Thank you for visiting, please update your bookmarks.

Wednesday, February 13, 2008

ActionScript Class for Global Variables in Flex

I've been reading several blogs and forums on how to implement global variables in a Flex application. It's tough to find an effective example of how to do this as most threads/comments are flooded with people crying foul that good programming doesn't need global variables.

While I agree for the most part I'm used to having some sort of config file in my applications which hold defined constants that are likely to change depending on the deployment or version of the application. Eg: In my php applications I keep database connection information in a config file so that i can easily switch between a development database or production database.

The best solution I've found to do this in a Flex Application is to include in the root directory of your Flex application a ActionScript class that contains properties for all the constants or global variables you'll need to define.

Action Script : Settings.as


package
{
public class Settings
{
static public var SiteUrl:String="http://www.mydomain.com";
}
}

Example MXML File Using Settings.as

<?xml version="1.0" encoding="utf-8"?>
<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml" layout="absolute"
xmlns="*">
<mx:Script>
<![CDATA[
import mx.controls.Alert;
private function testSettings():void
{
Alert.show( Settings.SiteUrl );
}
]]>
</mx:Script>
<mx:Button label="test" click="testSettings()"/>
</mx:Application>


Important things to make note of in this example you'll need xmlns="*" in the opening tag of any MXML file or component which needs access to the properties of Settings.as. You'll also need to make sure Settings.as is the root folder of your application.

2 comments:

  1. Perfect! Just what I was looking for. Thank you!

    ReplyDelete
  2. With this method, I obtain some warning in Flex builder like 'Data binding will not be able to detect assignements to "myVariable"'.

    I added "[Bindable]" just before the Settings class declaration. It changes nothing to the method, except for removing those annoying warnings.

    Thanks for this post anyway !

    ReplyDelete

Thank you for the comments.