Flash Document Class

Another improvement in ActionScript 3.0 and Flash 9 that should help clean up FLA files is the inclusion of a document class. This allows you to specify a custom class to serve as the root in your SWF file. Now there is no excuse for putting code inside your FLA. ;)

Currently in ActionScript 2.0 I’ve been using a technique for simulating a document class. I’ve been using this for years and I’m happy to replace it with the built-in document class feature.

First, you’ll need to create a class (it must extend MovieClip) to serve as your document class. Inside this class we’ll add a static main method that will asign our class to the target refrence. (the target will be _root of our SWF)

1
2
3
4
5
class MainController extends MovieClip {
 public static function main(target:MovieClip):Void {
  target.__proto__ = MainController.prototype;
 }
}

Then, on frame one inside your FLA (yes, I know, one line of code in the FLA) you put the following line of code

1
MainController.main(this);

One thing you should note about this technique is that the constructor of the MainController class will not be called. Therefore, I usually add an init method and call it from inside the static main method like this:

1
2
3
4
5
6
7
8
9
class MainController extends MovieClip {
 private function init():Void {
  // Do Something
 }
 public static function main(target:MovieClip):Void {
  target.__proto__ = MainController.prototype;
  target.init();
 }
}

UPDATE: From reading a similar post on Keith Peters blog one of the comments shows a way to call the constructor of your class. The following is the revised code:

1
2
3
4
5
6
7
8
9
class MainController extends MovieClip {
 private function MainController () {
  // Constuctor
 }
 public static function main(target:MovieClip):Void {
  target.__proto__ = MainController.prototype;
  Function(MainController).apply(target, null);
 }
}

Leave a Reply

Your email address will not be published. Required fields are marked *