Among one of the coolest things I came across in Flash’s Actionscript 3 is the class ‘getDefinitionByName’. What it does (in short) is turning a class name in the form of a String into a class you can create an instance from. What this means is, you can create most flexible class creation built on cases.
E.g. instead of building a long switch…case list, you can add string names based on the elements an instance should have and call the specific class.
I use it for example to have a component that can call clips and bitmaps graphics from the library. The clip name can be handed over by XML and the appropriate clip can be added, without re-render or re-coding of the component.
I also build a centralized component-mediator control, that stores all possible pairs, so whenever I call for a component to be used in a mediator, it calls the right class. Which let’s me leave the display engine as is and only the content central changes from application to application.
Here is how I use it in a pureMVC environment:
var tMediatorClass:Class=getDefinitionByName(myMediatorClassName) as Class;
facade.registerMediator(new myMediatorClass(myComponent.id,myComponent));
There is though, one tricky issue. As long as you don’t mention a class’ name in the code, the compiler won’t implement it, meaning that your app will throw an error. Therefore, I changed my code to this:
var tMediatorClass:Class=getDefinitionByName(myMediatorClassName) as Class;
switch (myMediatorClass.NAME) {
case BasicMediator.NAME :
case EventMediator.NAME :
facade.registerMediator(new myMediatorClass(myComponent.id,myComponent));
}
I think I am still saving quite some lines here, especially given that a project can have a fir mount of mediators and components.
If you want to get a bit more chat on this one, read my conversation with the nice guys at actionscript.org