explorers’ club


getDefinitionByName trick
Thursday, February 21, 2008, 11:20 pm
Filed under: actionScript, components, development, flash, flex

I am in the process of working on a ClassUtil class that will have static methods for creating class instances from generic objects and xml objects. One thing that I use in order to create nested content within the outer-most object to be created is getDefinitionByName. If you are not familiar with this method check it out. It basically returns a Class object by provide the name of the class in a string format. You want a Class object of String, then you pass “String”. You want the Class object for com.somesite.model.vo.SomeVo, the you pass “com.somesite.model.vo.SomeVo” as the parameter and whallah! You just have to remember to use the fully qualified class path in the string parameter.

This technique combined with using describeType and others yields some pretty powerful results. More on that later tho. So the issue with using getDefinitionByName is that unless you have instantiated an instance of the class in question, your swf will contain the embedded class definition. Then you run into the run-time-error saying that the variable of that name cannot be found (or something like that).

The most common way to resolve this is to put a useless instance of the class somewhere in your application. Such as var foo:Foopher = null. Then the class definition of Foopher is embedded in the compiled swf. Someone please correct me if I am wrong in explaining this. The problem with this solution is it seems rather hacky. It just doesn’t settle well with me. So I sought a different path.

The more uncommon way to resolve this is to define your class with a static var like so:

package vo
{
import flash.net.registerClassAlias;
[RemoteClass(alias="vo.NestedObject")]
public class NestedObject {
static private var _isRegistered:Boolean = false;
public var id:uint;
public var name:String; public function NestedObject ()
{
if (!_isRegistered)
{
registerClassAlias("vo.NestedObject", NestedObject);
_isRegistered = true;
}
}
}
}

Now it may be that registerClassAlias is a bit expensive but seeing as it is done once and only once per class type, this shouldn’t pose a problem. The other benefit is that you don’t clutter unrelated classes or views with having to make dummy instances to get it to register. Lastly, you can pick and choose which classes to use this method on so as to limit the price of making the call.