In a recent project I was forced to dynamically generating UI Elements in flex from Strings. This is typically done using getDefinitionByName() as shown bellow. Although this works, in my app I never really know what the string is, nor do I know what the Class is named or where it is located. This becomes an issue since you must make reference to the Class somewhere in your code before it is available to the Flex framework.
This example shows the typical use of getDefinitionByName() with out any external SWC. Notice the imports and class references on the top of the Script block.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 | < ?xml version="1.0" encoding="utf-8"?> <mx:application xmlns:mx="http://www.adobe.com/2006/mxml" layout="vertical" xmlns:controls="com.controls.*"> <mx:script> < ![CDATA[ import flash.utils.getDefinitionByName; //You must import the classes and instantiate them import com.controls.TestControlA;TestControlA; import com.controls.TestControlB;TestControlB; private function loadTestClass(name:String):void { var ClassReference:Class = getDefinitionByName(name) as Class; var s:DisplayObject = (new ClassReference() as DisplayObject) testContainer.addChild(s); } ]]> </mx:script> <mx:vbox id="testContainer" /> <mx:hbox id="buttonBar"> <!--You have to place the entire package location in the string--> <mx:button label="Test A" click="loadTestClass('com.controls.TestControlA')" /> <mx:button label="Test B" click="loadTestClass('com.controls.TestControlB')" /> </mx:hbox> </mx:application> |
This won’t work since I need to make a reference to Classes that I won’t know the names of till run-time. My first step was to move a control into an external SWC, however I still am forced to make reference to the class so it becomes available, or I will get an error. This is a no go.
Popularity: 7% [?]









Social Links