Problem: An XML configuration file needs to be loaded at runtime and be ready when the application's createChildren() gets called. At the latest, because configuration values are needed to properly initialize child components. Preferably, I would like the configuration loading be complete before the application even gets created. In short, I want to do this:
- load configuration, then
- initialize the application using the loaded configuration.
I created a custom preloader to help solve this. But as it turns out, the application's createChildren() method already gets called during preloading, when the configuration is not yet guaranteed to be loaded. That is, before the custom preloader dispatches the COMPLETE event.
Thanks for any help in advance.
I found a solution to the problem. The key was to catch the preloader's FlexEvent.INIT_PROGRESS event, queue it, and stop its propagation until the configuration is fully loaded. This effectively stops the framework to proceed with application initialization. After the configuration loads, redispatch the queued events, letting the framework finish the preloading phase. Example code below (only relevant pieces):
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 the application:
<mx:Application preloader="the.package.of.PreloaderDisplay">
The simplest way (I think) is to create a 'holder' canvas that will create the applications content after the context file is loaded, ie:
(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>
来源:https://stackoverflow.com/questions/2773617/how-to-preload-a-file-in-flex-before-the-application-initializes