Current location: Oslo, Norway

Creating component instances from Strings in Flex

Posted on Thursday, May 29, 2008 @ 15:23 CET

Lets say you have a project where you have a data-set that you want to display in different ways. Also, the component that is to be used to display the data is sent over the wire from the server as a string, representing which ActionScript class to use. This is pretty simple to do in Flex by combining the powers of mx.core.ClassFactory and flash.utils.getQualifiedClassName, as shown below:

import flash.utils.getQualifiedClassName;
import mx.core.ClassFactory;
import com.paulofierro.components.*;

// A String representing the component class to use
var classToUse:String = "com.paulofierro.components.MyComponent";
// Get a reference to the component's class
var classRef:Class = getDefinitionByName(classToUse) as Class;
// Create factory object 
var factory:ClassFactory = new ClassFactory(classRef);
// Create a new instance of the component
var comp:* = factory.newInstance();
// And add it to stage
addChild(comp);

Although this works great, the only thing I would do is create an interface that the components then have to implement. That way you can keep up the strict typing and get code hints later when you're using the component, by doing the following when creating the instance:

var comp:IComponent = factory.newInstance();

A few days ago I came across this example over at the Flex cookbook, that shows how to swap itemRenderers at runtime. This just takes it one tiny step further.

- paulo

Post a comment:

You must have Flash and JavaScript enabled to post a comment.