There is a few primitives in the new Spark library introduced with the arrival of Gumbo. I want to instanciate a few of them dynamically (here SimpleText and VideoElement).
We're gonna use the getReferenceByName() method and the ClassFactory Flex Object. It allow us to dynamically instanciate object and set properties.
package com.palleas.components
{
import flash.utils.getDefinitionByName;
import mx.core.ClassFactory;
import mx.events.FlexEvent;
import spark.components.Application;
import spark.layouts.VerticalLayout;
import spark.primitives.SimpleText;
import spark.primitives.VideoElement;
import spark.primitives.supportClasses.GraphicElement;
public class Facade extends Application
{
// just to make it simply work
// more information about that later
private var uselessVideoElementVar:VideoElement;
private var uselessSimpleTextVar:SimpleText;
public static const DEFAULT_PACKAGE:String = "spark.primitives";
protected var factory:ClassFactory;
protected var componentList:Array = [
{ type:"SimpleText",
properties: { text:"Hi there, how are you ? I'm a simple text, cool huh ?", x:10, y:200 }},
{ type:"VideoElement",
properties: { source:"http://up.palleas.com/sample.flv", left:100, top:100 }}];
public function Facade()
{
super();
// factory used later
factory = new ClassFactory();
// waiting for the component to be fully created
addEventListener(FlexEvent.CREATION_COMPLETE,creationCompleteHandler);
}
/**
* This method is called when the component is ready
* It'll create every component and and them to the stage
* @param e
*
*/
protected function creationCompleteHandler(e:FlexEvent):void
{
removeEventListener(FlexEvent.CREATION_COMPLETE,creationCompleteHandler);
for each (var component:* in componentList)
{
// getting the full class
var componentClass:Class = getDefinitionByName(DEFAULT_PACKAGE+"."+String(component.type)) as Class;
factory.generator = componentClass;
factory.properties = component.properties;
// adding a new instance of the component we just created
addElement(factory.newInstance() as GraphicElement);
}
}
}
}
This is a simple example to illustrate a possible use of the ClassFactory Object. It would be very usefull in a web gallery in which you can have sounds, videos, images, some text, swf... This method is a lot more smart than a huge switch/case...
[1] We have to do this because if we don't, the components we use here (VideoElement and SimpleText) wouldn't be integrated to the compilation. There is a smarter solution called "RSL" (Runtine Shared Libraries), but it would have made this recipe a bit too long...