AS2: Document Class
In talking with people about the AS3 document class feature, it seems that many are unaware that more elegant entry point solutions exist than simply passing the document scope to a static method of the main application class in AS2. Though this approach works just fine, there are better ways to accomplish this. I am certainly not the first to blog about such a topic, however I thought I would share my favorite approach with all of you.
First off, I have a document utility class titled 'DocumentUtil'; inside of which I have a static method named 'RegisterClass'. This is where the link is made between the document and the main application class (thus creating a document class of sorts). Have a look:
-
// RegisterClass
-
//
-
// Registers the passed document and class together, thus creating a document class.
-
// The document class constructor is invoked upon this method being called.
-
public static function RegisterClass(mcDocument:MovieClip, objClass:Object):Void
-
{
-
// Set the prototype reference to the document classes constructor
-
// prototype property.
-
mcDocument.__proto__ = Function(objClass).prototype;
-
-
// Invoke the document class' constructor within the scope of the document.
-
Function(objClass).apply(mcDocument, null);
-
}
Now, on the first frame of the root timeline you do the following to initialize the application:
-
// Import the document utility class.
-
import com.boostworthy.utils.DocumentUtil;
-
-
// Import the class in which you wish to register as the document class.
-
import BallerApp;
-
-
// Register this document with the specified class.
-
DocumentUtil.RegisterClass(this, BallerApp);
And that is it. The constructor of the class will get called immediately and the scope within the class will be that of the document. Not quite as charming as the AS3 document class, however it will certainly do.
2 Comments so far
Leave a reply

Hey, thanks. This is a good approach that I was able to successfully implement on a project.
How would you then delete an instance created this way? I have a similar setup but removing the mcDocument ( mcDocument.removeMovieClip() ) doesn't delete the class instance just the movie clip.