Solitamente per questi casi si cerca di utilizzare classi singleton che prevedono una singola istanziazione della classe dando la possibilità a chi usa la classe di usare un metodo che solitamente viene chiamato getInstance() anche per assegnare eventi dispatchati all'interno della classe.
Codice PHP:
package {
import flash.events.Event;
import flash.events.EventDispatcher;
import flash.utils.setTimeout;
public class Singleton extends EventDispatcher {
private static var _instance:Singleton;
private static var _allowInstantiation:Boolean;
public function Singleton ():void {
if (!_allowInstantiation) throw (new Error("Error: Instantiation failed: Use Singleton.getInstance() instead of new."));
}
public static function getInstance ():Singleton {
if (_instance == null) {
_allowInstantiation = true;
_instance = new Singleton();
_allowInstantiation = false;
}
return _instance;
}
public static function testMethod (s:String=""):void {
trace(s);
setTimeout(Singleton.privateTestMethod, 1000);
}
private static function privateTestMethod ():void {
getInstance().dispatchEvent(new Event("test"));
}
}
}
Una classe del genere potrà essere usata così dentro ad un filmato flash:
Codice PHP:
Singleton.getInstance().addEventListener("test", testDrive);
Singleton.testMethod("prova");
function testDrive (evt:Event):void {
trace(evt);
}