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.
<?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.
Peter deHaan
Peter deHaan currently works for Adobe on the Flex SDK QA team. While not working on Flex, Flash, and ColdFusion applications, Peter enjoys making up bios and writing in 3rd person. Peter's rarely updated blog can be found at blogs.adobe.com/pdehaan/, actionscriptexamples.com, airexamples.com, and coldfusionexamples.com.
-
Add Widgets (Content Sidebar)
This is your Content Sidebar. Edit this content that appears here in the widgets panel by adding or removing widgets in the Content Sidebar area.
10 Responses to Creating a component instance by class name in ActionScript 3.0
Leave a Reply Cancel reply
-
Categories
- Accordion
- AccordionHeader
- ActionScript
- AddChild
- AdvancedDataGrid
- Alert
- alpha
- Animate
- AnimateProperties
- Application
- Application (Spark)
- ArrayCollection
- BarChart
- baseColor
- beta
- beta1
- beta2
- Bitmap
- Bitmap/BitmapData
- BitmapData
- BitmapFill
- BitmapFill (Spark)
- BitmapGraphic
- BitmapImage
- BitmapImage (Spark)
- BitmapImageResizeMode
- Border (Spark)
- BorderContainer (Spark)
- Box
- BuildInfo
- Button
- Button (Spark)
- ButtonBar
- ButtonBar (Spark)
- ByteArray
- Camera
- Charting
- CheckBox
- CheckBox (Spark)
- ClassFactory
- CollectionEvent
- Color
- ColorPicker
- ColorUtil
- ComboBox
- ComboBoxArrowSkin
- Compiler
- Component
- Component (Spark)
- Configuration
- Container
- ContextMenu
- ContextMenuEvent
- ContextMenuItem
- CSSCondition
- CSSSelector
- CSSStyleDeclaration
- CurrencyFormatter
- CursorManager
- Data Binding
- DataGrid
- DataGrid (Spark)
- DataGridColumn
- Date
- DateBase
- DateChooser
- DateField
- DateFormatter
- Debugging
- DefaultComplexItemRenderer
- DefaultTileListEffect
- DropDownList
- DropDownList (Spark)
- DropDownListButtonSkin
- DropDownListSkin
- DropShadowFilter
- E4X
- Effects
- Ellipse
- EmailValidator
- Embed
- Event
- Fade
- FileFilter
- FileReference
- fill
- Filters
- Flash
- Flash Integration
- FlashVars
- Flex 3 SDK
- Flex Builder
- Flex Builder 3
- Flex SDK
- Flex4
- FLVPlayback
- FocusManager
- FontLookup
- Fonts
- Form
- Form (Spark)
- FormHeading (Spark)
- FormItem
- FormItem (Spark)
- Forms
- FTETextField (Spark)
- FullScreen
- FullScreenEvent
- FxAnimateColor
- FxButtonBar
- FxCheckBox
- FXG
- FxHScrollBar
- FxHSlider
- FxList
- FxNumericStepper
- FxRadioButton
- FxRotate3D
- FxScroller
- FxTextArea
- FxTextInput
- FxToggleButton
- FxVScrollBar
- FxVSlider
- getStyleDeclaration()
- GradientEntry
- Graphic (Spark)
- HBox
- HDividedBox
- HGroup (Spark)
- HorizontalLayout
- HorizontalList
- HSBColor (Spark)
- HScrollBar (Spark)
- HSlider
- HSlider (Spark)
- HTML template
- ID3Info
- Image
- Image (Spark)
- ImageSnapshot
- itemRenderer
- JointStyle
- Label
- Label (Spark)
- Legend
- LegendItem
- LigatureLevel
- Line
- LinearGradientStroke
- LineScaleMode
- LinkBar
- LinkButton
- List
- List (Spark)
- Menu
- MenuBar
- Metadata
- MetadataEvent
- Model
- Mouse
- MouseCursor
- MouseEvent
- Move
- Namespace
- NavigatorContent (Spark)
- needsSWF
- NetConnection
- NetStream
- Nightly Builds
- NumberBaseRoundType
- NumberFormatter
- NumberValidator
- NumericCompare
- NumericStepper
- NumericStepper (Spark)
- ObjectProxy
- ObjectUtil
- paddingLeft
- paddingRight
- Panel
- Panel (Spark)
- Parallel
- Path
- PieChart
- PieSeries
- PieSeriesItem
- PopUpAnchor (Spark)
- PopUpButton
- PopUpManager
- ProgrammaticSkin
- ProgressBar
- PropertyChangeEvent
- QName
- RadialGradient
- RadioButton
- RadioButton (Spark)
- RadioButtonGroup
- RadioButtonGroup (Spark)
- Rect
- RegExp
- Regular Expressions
- Repeater
- RichEditableText
- RichText
- RichText (Spark)
- RichTextEditor
- Rotate
- Rotate3D (Spark)
- Scroller (Spark)
- Sequence
- setStyle()
- SimpleText
- SimpleText (Spark)
- skinClass
- Slider
- SliderEvent
- SolidColor
- SolidColorStroke
- Sort
- SortField
- Sound
- SoundEffect
- Spinner (Spark)
- SpriteVisualElement (Spark)
- StageDisplayState
- States
- StringUtil
- StringValidator
- StyleManager
- Styles
- SWFLoader
- SWFObject
- System
- SystemManager
- TabBar
- TabBar (Spark)
- TabNavigator
- TabStopFormat
- Text
- Text Layout Framework (TLF)
- TextArea
- TextArea (Spark)
- TextBox
- TextConverter
- TextEvent
- TextFlow
- TextFlowUtil
- TextFormat
- TextGraphic
- TextInput
- TextInput (Spark)
- TextLayoutFormat
- TextView
- Themes
- TileLayout
- TileList
- TileOrientation
- Timer
- TitleWindow
- TitleWindow (Spark)
- TLF
- ToggleButton (Spark)
- ToggleButtonBar
- ToolTip
- Transition
- Tree
- TruncationOptions
- UIComponent
- UIFTETextField
- Updater
- URLLoader
- URLRequest
- URLUtil
- URLVariables
- ValidationResultEvent
- Validator
- Validators
- VBox
- VDividedBox
- Vector
- VerticalLayout
- VerticalLayout (Spark)
- VGroup (Spark)
- Video
- VideoDisplay
- VideoElement
- VideoElement (Spark)
- VideoEvent
- VideoPlayer (Spark)
- VideoPlayerScrubBar
- ViewStack
- VScrollBar (Spark)
- VSlider
- VSlider (Spark)
- XML
- XMLList
- XMLListCollection
- ZipCodeValidator
- ZipCodeValidatorDomainType
- Zoom
-
Articles
- December 2010
- November 2010
- October 2010
- September 2010
- August 2010
- July 2010
- June 2010
- May 2010
- April 2010
- March 2010
- February 2010
- January 2010
- December 2009
- November 2009
- October 2009
- September 2009
- August 2009
- July 2009
- June 2009
- May 2009
- April 2009
- March 2009
- February 2009
- January 2009
- December 2008
- November 2008
- October 2008
- September 2008
- August 2008
- July 2008
- June 2008
- May 2008
- April 2008
- March 2008
- February 2008
- January 2008
- December 2007
- November 2007
- October 2007
- September 2007
- August 2007
- July 2007
-
Meta


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.
andrew,
You could use
getChildAt()orgetChildByName()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
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!
…note that the second line should read:
var obj:UIComponent = new c();
andrew,
Try using
main.getChildByName()instead:var i:Image = main.getChildByName("54237") as Image;Peter
Yes! That was it.
It took me about 5 hours to figure this one out.
You rock!
Andrew.
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
How about an icon or image class
e.g.
[Bindable][Embed("assets/iconset/save.png")]
public var saveIcon:Class;
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);
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?