Using event listeners on a static class

Scribbled the 14 January 2010 in Flash/Flex development

This post will show you how to use the methods addEventListener and removeEventListener on a static class.

Why?

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.

Let’s look at some code

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);
        }
    }
}

Conclusion

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


Enlighten me with your commentary

Submit comment


Categories

Flash/Flex development
Freelancing
Linux
Web development

Archive


About


My name is Richard Zetterberg and I'm an flash/flex developer with a lot of creative ideas and a designer background.

The purpose of this blog is to write about experiments I've done or about solutions to problems I've dealt with over the time I've been programming.


Search


Contact

richard [at] paralyzed [dot] se


Social networking