ExpatTech Techblog

Peter Todd 2010.11.02. 11:37

Flash Cookbook - Tricks - GetDefinitionByName

Sometimes it's really handy to use the flash.utils.getDefinitionByName function. This gives you a dynamic instance creation especially if you use an object model description for your application. Let's say you created an xml with items, each describes an object with a classname. Then you can generate the objects with a loop, using the getDefinitionByName function.

var classbyname:Class = getDefinitionByName(classname) as Class;
var object:* = new classbyname();

This can be done with the code below too:

if(classname == SOME_CLASS_NAME) var object:* = new SOME_CLASS_NAME();

This case you don't need the getDefinitionByName() function, but you loose the chance to create your code fully dynamic. You always have to come back to this part of the code and add a new case if you create a new class. Using getDefinitionByName() doesn't need this, but of course it's not without any further todos.

Actually, in Adobe Flash CS4 when you create a new symbol and export it for Actionscript, you can see a checkbox: "Export in frame 1". This makes sure, you initialized your class in your application, and from now, you can reach it anywhere with for example getDefinitionByName().

The trick comes now. What if you don't use this method and only writing code? What if you completely avoid using the functions of the IDE? Then the trick is easy:

anywhere in your code put a "new SOME_CLASS_NAME()" initialization. You don't have to use this specific instance, but initializes it, so basically it equals to "Export to frame 1".

Furthermore, you don't really need to create the instance. Practically it's enough to put "SOME_CLASS_NAME" in your code. Surpirising, but works.