Making your ActionScript 3/Flex project work correctly in both development and production
Posted by Ian Serlin | Tweet This | Filed under Actionscript 3, Javascript, problem solution
Very often there will be multiple environments that your application will be running under whether just for testing purposes or even multiple deployment domains. When running in a dev or test environment it can be useful or necessary to mock input/output or even just modify any urls your app is using if relative addresses aren’t an option. If you’re creating an embeddable application it might be nice to know when your swf is loaded on your own domain versus a 3rd party’s.
In any case, you could write build scripts or you could manually change command-line compiler options or add them in Flex/Flash Builder or even just edit some xml config files before you deploy. For the most part, in most cases, that sucks. Repetitive non-thinking work sucks because you don’t like it and you’ll forget to do it and then all of a sudden shit will hit the fan in production because you forgot to update some random variable you’d rather forget about.
Problem
You want your application to operate appropriately in whatever supported environment it’s run under.
Solution
If you’ve set up different domains to run your dev, test and production environments under (you should, just modify your hosts file) you can simply grab the url of the page your application was loaded in and switch your logic to use the correct server urls or whatever fork needs to happen based on environmental changes (good architecture should keep these forks to a minimum). The following function gets the base url for you:
1 2 3 4 5 6 7 | public static function getWindowLocationBaseURL():String { if( ExternalInterface.available ){ var url:String = ExternalInterface.call( "function () { return window.location.protocol.toString().toLowerCase() + '//' + window.location.host.toString().toLowerCase(); }" ); return url; } return ""; } |
Then you can just do a:
1 | if( getWindowLocationBaseURL().indexOf( "example.test" ) != -1 ){ ... } |
to see what environment you’re running under.
Gotchas
The one nice thing about using build scripts or configs to solve this problem is that you can do conditional compilation which will reduce your final swf size. In my experience though the amount of additional space required to do the above is negligible, especially compared to satisfaction of not having to worry about it anymore.
How did you tackle the issue of multiple runtime environments? Let me know in the comments!