How to preload a file in Flex before the application is initialized
Problem: The XML configuration file must be loaded at runtime and ready when the createChildren () application is called. Last but not least, because config values are needed to properly initialize child components. It is advisable that the configuration load is completed before the application is even built. In short, I want to do this:
- load the config, then
- initialize the application using the loaded configuration.
I created a dedicated preloader to help solve this problem. But as it turns out, the createChildren () method has already been called during preload, when the configuration is not yet guaranteed to load. That is, before the custom preloader dispatches the COMPLETE event.
Thanks for any help in advance.
a source to share
I found a solution to the problem. The key was to catch the FlexEvent.INIT_PROGRESS preloader event, enqueue it and stop it propagating until the configuration is fully loaded. This actually stops the framework from continuing to initialize the application. Once the configuration is loaded, forward the events in the queue, allowing the framework to complete the preload phase. Sample code below (relevant snippets only):
public class PreloaderDisplay extends Sprite implements IPreloaderDisplay {
// mx.preloaders.IPreloaderDisplay interface
public function set preloader(preloader:Sprite):void {
// max priority to ensure we catch this event first
preloader.addEventListener(FlexEvent.INIT_PROGRESS, onInitProgress, false, int.MAX_VALUE);
startLoadingConfiguration();
}
private function onInitProgress(e:FlexEvent):void {
if (isConfigurationLoading) {
queuePreloaderEvent(e);
e.stopImmediatePropagation();
}
}
private function onConfigurationLoaded():void {
dispatchQueuedPreloaderEvents();
}
}
To use it in an application:
<mx:Application preloader="the.package.of.PreloaderDisplay">
a source to share
The easiest way (I think) is to create a canvas "holder" that will create application content after loading the context file, i.e.
(psuedo code)
Application.mxml:
<mx:Canvas>
<mx:Script>
public function init():void{
loadXML();
}
public function handleXMLLoaded():void{
this.addChild(myApplicationContent);
}
</mx:Script>
</mx:Canvas>
MyApplicationContent.mxml
<mx:Canvas>
<!-- contains all your components etc -->
</mx:Canvas>
a source to share