Archive for actionscript 2

AS2 History class: The construct function

Posted in Actionscript, Development, oop with tags , , , , , , on July 3, 2011 by andkrup

Here’s a little nugget of information that may or may not come in handy. If javascript is to get the revival that everybody is hoping for (with html5 and ajax), this kind of code could prove useful, especially since we’re touching on some common concepts (mostly prototype manipulation).

Also, if you are being forced to develop something for the flash museum, you might need this snippet of code.

But first, some history lecture…

The problem

Most of the time a flash developer is to develop a larger flash application, he wants to have control of the main timeline. As3 developers have it easy with the possibility of creating a Document class and flex coders extends the Application class all the time.

In flash 8 we typically added scripts in the top-most timeline in_level0 but there where always some problems with this approach, especially in modular applications where you could only cast a loaded swf file as a MovieClip and hope that that instance had had some function references added to it, with execution scope being addressed correctly.

Normal MovieClip symbols from the library could map to external as2 classes fine, but the _level0 timeline was out of reach, even though it behaves just like any other normal MovieClip symbol, when loaded into another swf file.

In as3 this architectural problem was addressed with the advent of the Document class, but you can actually do the same in as2:

The Solution

class Main extends MovieClip{
static var instance:Main;
public static function construct(timeline):Void{
if(!instance){
timeline.__proto__ = Main.prototype;
Function(Main).apply(timeline, arguments.slice(1));
instance = (Main)(timeline);
}
}

public function Main(){
}
}

Invoke the static construct method in _level0 in your 2004-tech flash file, with ‘this’ as the first argument like so:

Main.construct(this);

 

What this method does, is that it replaces the _level0 hidden property __proto__ with the one from your external as2 class, invokes your external as2 classes constructor and in practicality casts _level0 (with the new prototype inheritance chain) as an instance of your external as2 class.

This means that whenever we need to develop modular flash in yesterdays technology, we can stay comfortably in the OO-zone (especially if we also create and implement some interfaces to establish an api), and use _level0 as an instance of your ‘Document’ class

Very nice.

Advertisements