ActionScript Class for Global Variables in Flex
原文:
http://www.kerkness.ca/?p=4
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.