Flex Tip 7: Using Deferred Instantiation

March 26, 2008 – 2:02 pm

When you are using MXML containers and declare the children as MXML tags inside the component, there is a possibility to not load all child components at instantiation, possibility known as “deferred instantiation”. That is, the instantiation is deferred by an amount of time depending on creationPolicy property of Container class. This is the property that sets the rules in creation of child components:

- a creationPolicy of ContainerCreationPolicy.AUTO means that the container delays creating some or all descendants until they are needed. This policy produces the best startup time because fewer UIComponents are created initially.

- a creationPolicy of ContainerCreationPolicy.QUEUED means that the container is added to a creation queue rather than being immediately instantiated and drawn. When the application processes the queued container, it creates the children of the container and then waits until the children have been created before advancing to the next container in the creation queue.

- a creationPolicy of ContainerCreationPolicy.NONE means that the container creates none of its children. In that case, it is the responsibility of the MXML author to create the children by calling the createComponentsFromDescriptors() method.

The version we are interested in is ContainerCreationPolicy.NONE when instantiation of children is let it developer’s hand. So lets go ahead and create a simple component:

<?xml version="1.0" encoding="utf-8"?>
<mx:Canvas xmlns:mx="http://www.adobe.com/2006/mxml">
   
    <mx:TextInput width="120" />
   
    <mx:Button x="130" label="Example 1" />
   
    <mx:TextInput y="25" width="120" />
   
    <mx:Button x="130" y="25" label="Example 2" />
   
</mx:Canvas>

Save this as SimpleContainer.mxml in your project and in the main application file use the following code:

<?xml version="1.0" encoding="utf-8"?>
<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml" layout="absolute" xmlns:local="*">
   
    <mx:Script>
    <![CDATA[
   
    private function displayForm():void
    {
        container.createComponentsFromDescriptors();
    }
   
    ]]>
    </mx:Script>
   
    <mx:Button x="100" label="Display Form" click="displayForm()" />
   
    <local:SimpleContainer id="container" creationPolicy="none" />
   
</mx:Application>

Note the creationPolicy="none" attribute on SimpleContainer instance. Also note the container.createComponentsFromDescriptors();. This line calls the createComponentsFromDescriptors method from the container that will parse the array containing all objects describing the children components and instantiate the visual child components.

This is a nice way to keep your initial state of components clean and display child components only when needed. Go here for source code.

Post a Comment