28
Aug
08

Creating a component instance by class name in ActionScript 3.0

The following example shows how you can create a new Flex component instance by using its class name by calling the getDefintionByName() method.

Full code after the jump.

In the following example, note that we must include a reference to each of the components we may need to create at runtime in a variable, dummyArr. This way, the components we need are compiled in to the SWF so they can be created at runtime.

View MXML

<?xml version="1.0" encoding="utf-8"?>
<!-- http://blog.flexexamples.com/2008/08/28/creating-a-component-instance-by-class-name-in-actionscript-30/ -->
<mx:Application name="getDefinitionByName_test"
        xmlns:mx="http://www.adobe.com/2006/mxml"
        layout="vertical"
        verticalAlign="middle"
        backgroundColor="white">

    <mx:Script>
        <![CDATA[
            import mx.core.UIComponent;
            import flash.utils.getDefinitionByName;
            import mx.controls.*;

            /**
             * Create references to component classes so the classes get
             * included in the SWF document.
             */
            private var dummyArr:Array = [Button, CheckBox, ComboBox,
                                            List, TextInput, TextArea];

            private function createBtn_click(evt:MouseEvent):void {
                var className:String = comboBox.selectedItem.toString();
                // Convert class name to Class object.
                var cls:Class = getDefinitionByName(className) as Class;

                // Create a new instance of the class.
                var instance:UIComponent = new cls();
                if (instance) {
                    switch (instance.className) {
                        case "Button":
                            Button(instance).label = "I am a Button";
                            break;
                        case "CheckBox":
                            CheckBox(instance).label = "I am a CheckBox";
                            break;
                        case "ComboBox":
                            ComboBox(instance).dataProvider = ["I am a ComboBox"];
                            break;
                        case "List":
                            List(instance).dataProvider = ["I am a List"];
                            instance.width = 100;
                            break;
                        case "TextInput":
                            TextInput(instance).text = "I am a TextInput";
                            break;
                        case "TextArea":
                            TextArea(instance).text = "I am a TextArea";
                            break;
                    }

                    // Remove all children and add new child.
                    canvas.removeAllChildren();
                    canvas.addChild(instance);
                }
            }
        ]]>
    </mx:Script>

    <mx:ApplicationControlBar dock="true">
        <mx:Form styleName="plain"
                defaultButton="{createBtn}">
            <mx:FormItem label="Class:"
                    direction="horizontal">
                <mx:ComboBox id="comboBox">
                    <mx:dataProvider>
                        <mx:Array>
                            <mx:String>mx.controls.Button</mx:String>
                            <mx:String>mx.controls.CheckBox</mx:String>
                            <mx:String>mx.controls.ComboBox</mx:String>
                            <mx:String>mx.controls.List</mx:String>
                            <mx:String>mx.controls.TextInput</mx:String>
                            <mx:String>mx.controls.TextArea</mx:String>
                        </mx:Array>
                    </mx:dataProvider>
                </mx:ComboBox>
                <mx:Button id="createBtn"
                        label="Create"
                        click="createBtn_click(event);" />
            </mx:FormItem>
        </mx:Form>
    </mx:ApplicationControlBar>

    <mx:Canvas id="canvas"
            horizontalCenter="0"
            verticalCenter="0" />

</mx:Application>

View source is enabled in the following example.


6 Responses to “Creating a component instance by class name in ActionScript 3.0”


  1. 1 andrew Sep 3rd, 2008 at 9:54 am

    Thanks for the code. Works perfect.

    Let’s say you created 10 components. And then you want to reference those components in actionscript. How would you do so?

    For example, let’s say you wanted to dynamically change the background of one of the components. How you you write the actionscript (instance.backgrouColor = #000000 ??? )

    Andrew.

  2. 2 peterd Sep 3rd, 2008 at 10:32 am

    andrew,

    You could use getChildAt() or getChildByName() to access the dynamically created component instances. Something like the following:

    <?xml version="1.0" encoding="utf-8"?>
    <mx:Application xmlns:mx="http://www.adobe.com/2006/mxml"
            layout="vertical"
            verticalAlign="middle"
            backgroundColor="white"
            creationComplete="init();">
    
        <mx:Script>
            <![CDATA[
                import flash.utils.getDefinitionByName;
                import mx.controls.Button;
    
                private const dummyArr:Array = [Button];
    
                private function init():void {
                    var c:Class = getDefinitionByName("mx.controls.Button") as Class;
                    var idx:uint;
                    var len:uint = 5;
                    for (idx = 0; idx < len; idx++) {
                        var obj:Button = new c();
                        obj.label = "Button " + idx;
                        obj.name = "button" + idx;
                        addChild(obj);
                    }
                }
    
                private function btn_click(evt:MouseEvent):void {
                    var b:Button = getChildByName("button3") as Button;
                    b.label = "OUCH";
                }
            ]]>
        </mx:Script>
    
        <mx:ApplicationControlBar dock="true">
            <mx:Button id="btn"
                    label="Change Button 3"
                    click="btn_click(event);" />
        </mx:ApplicationControlBar>
    
    </mx:Application>
    

    Peter

  3. 3 andrew Sep 3rd, 2008 at 11:42 am

    Thank you so much Peter - that makes a lot of sense.However, for some reason, my code is throwing an error: “Cannot accesss the property of a null object…”

    This is my code in a nutshell:

    The following code is in a loop where “contentType” changes between Text, TextArea and Image. It outputs perfectly (thanks to you!).

    var c:Class = getDefinitionByName('mx.controls.'+contentType) as Class;
    var obj:UIComponent = new c();
    
    if (obj) {
    switch (obj.className) {
        case "Text":
            Text(obj).id = contentID;
            Text(obj).text = content;
            Text(obj).x = contentxPos;
            Text(obj).y = contentyPos;
            Text(obj).width = contentWidth;
            Text(obj).height = contentHeight;
            Text(obj).styleName = contentStyleName;
            break;
        case "TextArea":
            TextArea(obj).id = contentID;
            TextArea(obj).text = content;
            TextArea(obj).x = contentxPos;
            TextArea(obj).y = contentyPos;
            TextArea(obj).width = contentWidth;
            TextArea(obj).height = contentHeight;
            TextArea(obj).styleName = contentStyleName;
            break;
        case "Image":
            Image(obj).name = "54237";
            Image(obj).id = contentID;
            Image(obj).source = contentSource;
            Image(obj).x = contentxPos;
            Image(obj).y = contentyPos;
            Image(obj).width = contentWidth;
            Image(obj).height = contentHeight;
            Image(obj).setStyle('completeEffect', slowFade);
            Image(obj).addEventListener(MouseEvent.CLICK, showImageGallery);
            Image(obj).addEventListener(FlexEvent.CREATION_COMPLETE, creationCompleteHandler);
            break;
    }
    main.addChild(obj);
    }
    

    …but then I use:

    var i:Image = getChildByName("54237") as Image;
    i.source = '/myimage.jpg';
    

    And it doesn’t work. Note that I just hardcoded “54237″ for testing…

    Any suggestions ???

    Thanks again!

  4. 4 andrew Sep 3rd, 2008 at 11:47 am

    …note that the second line should read:
    var obj:UIComponent = new c();

  5. 5 peterd Sep 3rd, 2008 at 12:44 pm

    andrew,

    Try using main.getChildByName() instead:

    var i:Image = main.getChildByName("54237") as Image;
    

    Peter

  6. 6 andrew Sep 3rd, 2008 at 1:05 pm

    Yes! That was it.

    It took me about 5 hours to figure this one out.

    You rock!

    Andrew.

Leave a Reply

This blog is terrible at eating HTML tags. If you plan on posting code/XML, please escape your "<" characters as "&lt;" and your ">" characters as "&gt;".