This post will show you how to use the methods addEventListener and removeEventListener on a static class.
This is useful when you want to have a class which all classes can listen to events for. For example you have a class which loads some type of assets and you want to be able to know in multiple classes when that class has finished loading. This way you don’t have to pass around the instance for that loader class to all classes who needs to know when you have finished loading.
Since the addEventListener and removeEventListener aren’t static methods we have to create them ourselves. But which object will recieve the event listener? It can’t be the class itself because then we have to instantiate it. Instead we add a dispatcher as a variable in the class. Like this:
package{
public class StaticDispatcher{
private static var eventDispatcher:EventDispatcher = new EventDispatcher();
public static function addEventListener(type:String, callback:Function):void{
eventDispatcher.addEventListener(type, callback);
}
public static function removeEventListener(type:String, callback:Function):void{
eventDispatcher.removeEventListener(type, callback);
}
}
}
Very easy, but really powerful. I used this in a loader class which had multiple loaders, to be able to know when all the loaders where finished.
I guess it’s another way of using that class as a singleton. Usually you instantiate the class and then add code so that you can only do it once, and then make that instance globally accessable. But this way works really good. I hope someone will find this useful.
Richard Zetterberg