Flex Example: createChild and destroyChild

Posted on December 13, 2005 | 1 comment

Create three files called CreateDestroyChild.mxml, VBoxPage.mxml and PanelPage.mxml.

CreateDestroyChild.mxml:

<?xml version="1.0" encoding="utf-8"?>
<mx:Application xmlns:mx="http://www.macromedia.com/2003/mxml" xmlns="*"
    width="100%" height="100%" initialize="createUI( 'pageVBox' )">
   
    <mx:Script>
        <![CDATA[
            import mx.core.UIObject;
            public var pageItem : Object;
           
            function createUI( pageUI:String ):Void {
                if( pageUI == "pageVBox" )
                    pageItem = vsPageHolder.createChild( VBoxPage, undefined );        
                if( pageUI == "pagePanel" )
                    pageItem = vsPageHolder.createChild( PanelPage, undefined );           
            }

            public function destroyUI():Void {
                vsPageHolder.destroyChild( UIObject( pageItem ) );
            }          
        ]]>
    </mx:Script>
    <mx:HBox width="100%" textAlign="center">
        <mx:ComboBox id="cmbPages" change="destroyUI();createUI( cmbPages.selectedItem.data );">
            <mx:dataProvider>
                <mx:Array>
                    <mx:Object data="pageVBox" label="Page with VBox"/>
                    <mx:Object data="pagePanel" label="Page with Panel"/>
                </mx:Array>
            </mx:dataProvider>
        </mx:ComboBox>
        <mx:Button label="Destroy UI" click="destroyUI();" />
        <mx:Button label="Create UI" click="createUI( cmbPages.selectedItem.data );" />    
    </mx:HBox>
    <mx:ViewStack id="vsPageHolder" width="100%" height="100%">
    </mx:ViewStack>
</mx:Application>

VBoxPage.mxml

<?xml version="1.0" encoding="utf-8"?>
<mx:VBox xmlns:mx="http://www.macromedia.com/2003/mxml"
    width="200" height="200"
    backgroundColor="0x996633">
    <mx:Text text="VBox Page, Hello World!"/>
</mx:VBox>

PanelPage.mxml:

<?xml version="1.0" encoding="utf-8"?>
<mx:Panel xmlns:mx="http://www.macromedia.com/2003/mxml"
    width="300" height="300"
    backgroundColor="0x336699">
    <mx:Text text="Panel Page, Hello World!"/>
</mx:Panel>

This simple example shows the power of dynamically creating and destroy components at runtime.

  • Joan-Marie Ryan

    Hi Renaun,

    Would you have the above example in flex 2? I need to dynamically create views and add them to a viewstack. Your example would be a great starting point for me.

    Thanks in advance,
    Joan-Marie