EventDispatcherList AS3 Class

Custom class dependencies: None

I hope this class will be of as much help to everyone as it is to me. Too many times to count, I needed to manage multiple objects that all use the same listener! Adding the same listener to multiple objects is very useful and code saving in Actionscript 3. Most of the time though when you must do this, you still must manage the adding and removing of those listeners for each individual object. This class attempts to manage that in a more organized yet still open-ended fashion.

The simplest way I can describe it is a list, that you can add and remove listeners for each of its items with one call. It of course is not an Array though because it uses the Dictionary class to hold the data.

You simply add things to the list with the add(obj:*) method, and remove things with the remove(obj:*) method. Then to add and/or remove listeners you simply do so regularly but referencing the instance of EventDispatcherList instead of all of it’s objects individually.

Within the class everything is organized in Dictionaries so the keys are direct references to objects so we don’t have to worry about string or index keys being overwritten somewhere else. This also allows for each object in the list to register it’s own individual listeners in conjunction with the listeners from the list it is a part of. Using a Dictionary ensures listeners added to the list are ALWAYS registered as unique listeners, even if a listener added individually is registered with the same event type and listener function.

URLLoader Example

If you have 4 URLLoaders, all of them loading separate things, but at the same time. You want to listen for when ALL 4 URLloaders have completed. You would simply do this:

import com.jidd.events.EventDispatcherList;

var completed:int = 0;

var loaders:EventDispatcherList = new EventDispatcherList();
loaders.add(new URLLoader(new URLRequest('http://www.jimisaacs.com')));
loaders.add(new URLLoader(new URLRequest('https://jidd.jimisaacs.com')));
loaders.add(new URLLoader(new URLRequest('http://www.google.com')));
loaders.add(new URLLoader(new URLRequest('http://www.wikipedia.org')));

loaders.addEventListener(Event.COMPLETE, handleEvent);
loaders.addEventListener(IOErrorEvent.IO_ERROR, handleEvent);
loaders.addEventListener(SecurityErrorEvent.SECURITY_ERROR, handleEvent);

function handleEvent(e:*):void {
    trace(e);
    completed++;
    if(completed == loaders.items.length) {
        trace('ALL LOADERS COMPLETED');
    }
}

Like I said, this should streamline the process of managing multiple yet similar event dispatchers in a single object list format. Now I do have more classes and examples of how you may extend this class for more streamlined processes, those posts are to come… for now… Enjoy 😉

Comment if you have any questions, or suggestions.


Posted

in

, ,

by

Comments

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.