One of the really cool features of AS3 is that you specify a document class which extends MovieClip or Sprite, and that class is your application. As the class extends Sprite/MovieClip, “this” refers to the main timeline, _root, _level0, whatever you are used to thinking of it as.
In AS2 I’ve been using a static main function that passes in a ref to the main timeline and stores that in order to attach things, etc.:
[as]
class MyClass
{
private var target:MovieClip;
public static function main(target:MovieClip):Void
{
var app:MyClass = new MyClass(target);
}
public function MyClass(target:MovieClip)
{
this.target = target;
init();
}
private function init():Void
{
trace(“init”);
target.lineStyle(1, 0, 100);
target.lineTo(100, 100);
}
}
[/as]
Then, on the main timeline of the fla, you say:
[as]
MyClass.main(this);
[/as]
This has the advantage of working the same in both the IDE and in MTASC.
I was always pretty happy with this until I started using document classes. Now, having to prepend “target” every time I want to attach something, etc. seems a pain. So I started playing around with alternatives. I know I’m very far from the only one or even the first one to come up with a solution for this, but I figured I’d post it, if only for my own future reference. If someone else finds it useful, great.
Here’s what I came up with, that I’m pretty happy with:
[as]
class MyClass extends MovieClip
{
public static function main(target:MovieClip):Void
{
target.__proto__ = MyClass.prototype;
target.init();
}
private function init():Void
{
trace(“init”);
lineStyle(1, 0, 100);
lineTo(100, 100);
}
}
[/as]
The code in the fla is exactly the same:
[as]
MyClass.main(this);
[/as]
And it still works just fine with MTASC.
And it’s actually even smaller and simpler than my earlier method.
What it’s doing is replacing _root’s (or whatever movie clip you pass in) prototype with my document class’s. Of course, at that point, as _root has already been constructed, the document class’s constructor will never be called. So I just omitted it and called init directly.
With this setup, the class again is the main timeline. I can attach movie clips directly there, draw directly, whatever. Works for me.
Again, I’m sure I’m not the first one to come up with this. And I’m sure others have solutions that they find better. Feel free to share them.