Thursday, March 31, 2011

Understanding AS3 getDefinitionByName (for all eval maniacs)

Understanding AS3 getDefinitionByName (for all eval maniacs):

Sometimes you may want to create a new class or DisplayObject only starting from its name. This is where something like an eval function would come into play, but we have to manage it in a different way with AS3.

Look at this movie:

Circles are four different objects called symbol1, symbol2, symbol3 and symbol4 and this is the script:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
package {
 import flash.display.Sprite;
 public class Main extends Sprite {
  public function Main() {
   var s1:symbol1=new symbol1();
   addChild(s1);
   s1.x=95;
   s1.y=100;
   var s2:symbol2=new symbol2();
   addChild(s2);
   s2.x=245;
   s2.y=100;
   var s3:symbol3=new symbol3();
   addChild(s3);
   s3.x=395;
   s3.y=100;
   var s4:symbol4=new symbol4();
   addChild(s4);
   s4.x=545;
   s4.y=100;
  }
 }
}

Obviously it’s a bit unoptimized, just think about if we had a thousand objects. That’s when getDefinitionByName comes into play. It returns a reference to the class object of the class specified by the name parameter.

This means the same script can be written this way:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
package {
 import flash.display.Sprite;
 import flash.utils.*
 public class Main extends Sprite {
  public function Main() {
   var symbolName:String;
   var symbolClass:Class;
   var s:Sprite;
   for (var i:int=1; i<=4; i++) {
    symbolName="symbol"+i;
    symbolClass=getDefinitionByName(symbolName) as Class;
    s=new symbolClass();
    addChild(s);
    s.x=95+150*(i-1);
    s.y=100;
   }
  }
 }
}

DisplayObjects names are passed as strings in getDefinitionByName method and created as generic classes that can be used anywhere in the movie [...]

No comments:

Post a Comment