Creating a Class Dynamically in Flex Based on the Name
We're working on a Flex project at AboutWeb and wanted to use an object factory. Nic Tunney created an object factory in ColdFusion that uses an XML file for configuration. We were wondering if we could do the same thing in Flex. In order to do this we needed to be able to create a class dynamically based on a string value. A bit of research turned up the GetDefinitionByName function. Here's a sample of how it works:
<?xml version="1.0" encoding="utf-8"?>
<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml" layout="absolute" creationComplete="addButton()">
<mx:Script>
<![CDATA[
import flash.utils.getDefinitionByName;
private function addButton():void{
var className:String="mx.controls.Button";
var ClassReference:Class = getDefinitionByName(className) as Class;
var instance:Object = new ClassReference();
instance.label="Test"
this.addChild(DisplayObject(instance));
}
]]>
</mx:Script>
</mx:Application>
<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml" layout="absolute" creationComplete="addButton()">
<mx:Script>
<![CDATA[
import flash.utils.getDefinitionByName;
private function addButton():void{
var className:String="mx.controls.Button";
var ClassReference:Class = getDefinitionByName(className) as Class;
var instance:Object = new ClassReference();
instance.label="Test"
this.addChild(DisplayObject(instance));
}
]]>
</mx:Script>
</mx:Application>


Eg. var example:MyObject
That will make the compiler include the MyObject class within the swf
I ran into this when writing the Fling library (http://fling.riaforge.com), which serves as an "object factory" / IoC container, in the style of Spring / ColdSpring. Fling works around this by having you create a "configuration" application (compiles to a .swf) that references your concrete classes via binding. Your external app then loads the configuration swf into the factory, making the concrete classes available at runtime through factory methods (e.g., var bean:BeanInterface = beanFactory.getBean("ConcreteBean") as BeanInterface).
I'd recommend checking out Fling, it may be just the factory you're looking for.
-Joe
http://freeskullylayouts.com
Great guide guys keep up the good work.
Thanks for very interesting article.
Great guide guys keep up the good work.
Andrzej Filipowicz
Still life Artist, still life art
http://www.andrzejfilipowicz.com
STILL LIFE PAINTING
http://www.life.e-phils.com