I ran into a problem today where the most elegant solution was to dynamically instantiate a class. However, I couldn’t for the life of me figure out how to do that. Basically, the situation was this:
- Dispatch Event A
- If Event A Fails, Dispatch Event B, then re-dispatch Event A.
This dealt with a SQLite database and query statements. I want to run a Select query but if the table has not yet been created, I need to create the table then re-try the query. Here’s what I ended up doing…
In the fault of the select statement I dispatch the create table event and pass it an optional string (the class that I want to instantiate). In the create table command, I then dynamically create that class and instantiate it. Here’s the code:
Fault of Select Command:
new CreateTableEvent("com.test.cairngorm.events.SelectAllEvent").dispatch();
Create Table Event:
package com.test.cairngorm.events
{
import com.adobe.cairngorm.control.CairngormEvent;
public class CreateTableEvent extends CairngormEvent
{
public static const CREATE_TABLE_EVENT:String = "com.test.cairngorm.events.CreateTableEvent";
public var nextAction:String;
// constructor
public function CreateTableEvent(nextAction:String=")
{
this.nextAction = nextAction;
super( CREATE_TABLE_EVENT );
}
}
}
Result of Create Table Command:
// sourceEvent.nextAction is the string that I passed in
if( sourceEvent.nextAction.length )
{
// dynamically create a class based on the string
var c:Class = Class( getDefinitionByName( sourceEvent.nextAction ) );
// instantiate that class into a generic Object
var o:Object = new c();
// test if the object is a CairgormEvent.
// if so, dispatch that event
if( o is CairngormEvent )
CairngormEventDispatcher.getInstance().dispatchEvent(CairngormEvent(o));
}
Thank you very much to http://thillerson.wordpress.com/2007/03/01/runtime-class-instantiation-in-actionscript-30/ for pointing me in the right direction.

Related Articles
No user responded in this post
Leave A Reply