February 12th, 2007
Last week I tried to add 2 eventlisteners to the stage to listen for key up and key down events. These eventhandlers should be initiated immediately when the application is loaded. I added these eventlisteners to a function and called the function with the creationComplete() method in the application declaration. This setup gave me an error because the stage was not yet available and returned as a null object. I started digging into the event startup order of Flex and found that the stage was only available when called with the updateComplete() and applicationComplete() methods.
The creation order is different for containers and components because a container can be the parent of other components or containers. The following scheme shows the mayor events that are dispatched during the creation of a container:
So the order in which the events are dispatched by the application are preinitialize(), initialize(), creationComplete(), updateComplete() and applicationComplete().
The events in more detail:
– preinitialize() is dispatched when the component has been attached to its parent container, but before the component has been initialized, or any of its children have been created. In most cases, this event is dispatched too early for an application to use to configure a component.
– initialize() is dispatched when a component has finished its construction and its initialization properties have been set. At this point, all of the component’s immediate children have been created (they have at least dispatched their preinitialize() event), but they have not been laid out. Exactly when initialize events are dispatched depends on the container’s creation policy, as described later in this section.
– creationComplete() is dispatched when the component, and all of its child components, and all of their children, and so on have been created, laid out, and are visible.
– updateComplete() is dispatched every time the container or component characteristics are changed.
– applicationComplete() dispatches events after the Application has been initialized, processed by the LayoutManager and added to the display list. This is the last event dispatched during an application startup. It is later than the application’s creationComplete() event, which gets dispatched before the preloader has been removed and the application has been attached to the display list.
So you are trying to add eventListeners to the stage right from the start of your application execution, this will only work with updateComplete() and applicationComplete(). More information about the startup order of a Flex application can be found here.
Another solution for this is using the callLater() function.The callLater() function (or doLater() in previous versions of Flex and ActionScript), allows you to delay code execution until the user interface is updated.