I have a helper method has been created which allows a MovieClip-based class in code and have the constructor called. Unfortunately the solution is not complete because the MovieClip callback onLoad() is never called.
(Link to the Flashdevelop thread which created the method .)
How can the following function be modified so both the constructor and onLoad() is properly called.
//------------------------------------------------------------------------
// - Helper to create a strongly typed class that subclasses MovieClip.
// - You do not use "new" when calling as it is done internally.
// - The syntax requires the caller to cast to the specific type since
// the return type is an object. (See example below).
//
// classRef, Class to create
// id, Instance name
// ..., (optional) Arguments to pass to MovieClip constructor
// RETURNS Reference to the created object
//
// e.g., var f:Foo = Foo( newClassMC(Foo, "foo1") );
//
public function newClassMC( classRef:Function, id:String ):Object
{
var mc:MovieClip = this.createEmptyMovieClip(id, this.getNextHighestDepth());
mc.__proto__ = classRef.prototype;
if (arguments.length > 2)
{
// Duplicate only the arguments to be passed to the constructor of
// the movie clip we are constructing.
var a:Array = new Array(arguments.length - 2);
for (var i:Number = 2; i < arguments.length; i++)
a[Number(i) - 2] = arguments[Number(i)];
classRef.apply(mc, a);
}
else
{
classRef.apply(mc);
}
return mc;
}
An example of a class that I may want to create:
class Foo extends MovieClip
And some examples of how I would currently create the class in code:
// The way I most commonly create one:
var f:Foo = Foo( newClassMC(Foo, "foo1") );
// Another example...
var obj:Object = newClassMC(Foo, "foo2") );
var myFoo:Foo = Foo( obj );