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.

10 thoughts on “Creating a component instance by class name in ActionScript 3.0

  1. 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. 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. 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. Quote “we must include a reference to each of the components we may need to create at runtime in a variable”.

    How do we include a dynamic reference? Say, I have my own component called “MyButton”, which is dynamically loaded from database or xml file at runtime. In another word, I don’t the class name of my component at the coding/compiling time

  5. How about an icon or image class

    e.g.

    [Bindable][Embed(“assets/iconset/save.png”)]
    public var saveIcon:Class;

  6. solved the problem for icon/image class

    [Bindable][Embed(”assets/iconset/save.png”)]
    public var saveIcon:Class;

    ————————————————–
    var iconSource:String = “saveIcon”;

    var ImageClass:Class = this[iconSource] as Class;
    button.setStyle(“icon”, ImageClass);

  7. Hi, I know it’s old thread but I got similar problem as andrew and can’t find straight answer. All would be great but I use addElement in place of addChild. For examples sake let’s say I add a button with id “button1”. If I use mxml I can simply call it by using this[“button1”], but when I use pure ActrinScript I get an error saying that value doesn’t exists or is null. Only way I found so was was to make custom array and add reference to this component (array_name[“button1”]), but I don’t really like this way around and want to use this[“button1”] same like for mxml components. Could you point me in the right direction?

Comments are closed.