Home > ActionScript, Flash > Code Tip: The “getDefinitionByName” magic

Code Tip: The “getDefinitionByName” magic

I ran into a bit of a problem yesterday. You know when you define a class name in the Class field of the properties of a symbol present in flash library, whose Base class is your custom class and not native MovieClip (or any other native type). Say you have MySymbol_1, MySymbol_2 .. MySymbol_n present in your flash library. For which the class names are like SymbolClass_1, SymbolClass_2 .. SymbolClass_n which extend a Base class of SymbolBase. And if now you want to add those symbols on stage, you would ideally do:

this.addChild ( new SymbolClass_1 ());

or

var mySymbol :SymbolBase = new SymbolClass_1 ();
this.addChild ( mySymbol );

Now, here comes a situation (at least it was for me :)). What if you wanted to add a child whose class name is unknown up to a point when a user interacts. Say the user clicked on a button named as Button1, based on which SymbolClass_1 is supposed to be added. This is the solution I learnt a few days back. There is a getDefinitionByName public method available in the flash.utils package which allows you to get a class reference by the name parameter and then you can use that class reference and instantiate it in another variable of data type of your base class.

var myClassReference :Class = getDefinitionByName ( 'SymbolClass' + buttonNumber ) as Class;
var mySymbol :SymbolBase = new myClassReference;

This way, you can use dynamic variables in your class names and would instantiate the right class on demand. Btw, that is the solution I got, if anyone has any other solution/recommendation, please tell me.

About these ads
  1. clark
    September 23, 2011 at 12:35 pm

    keep blogging my Tahir! this helped me today when i referenced back to this blog post :)

    • September 23, 2011 at 12:37 pm

      Yeah I have been quite busy and ignoring this blog a lot. I will resume, I will resume blogging soon :)

  1. No trackbacks yet.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

Follow

Get every new post delivered to your Inbox.

%d bloggers like this: