Sometimes you need the ability to send events “through” the entire application. This can be useful, especially when you have a module-based architecture.
Imagine following situation: Multiple modules, one of them is periodically checking some server state. If this module detects an important change, maybe the user has logged out on the server side, or whatever, the other modules need to know about that change. So we need a component that broadcasts this change and anybody who is interested in that change listens for it. The change is broadcasted via Flash-Events and for the broadcasting itself, there is already the EventDispatcher. So the idea is to build a class that is simply holding a private static instance of an EventDispatcher and provides a dispatchEvent and addEventListener function, just like the EventDispatcher itself does.
{
import flash.events.Event;
import flash.events.EventDispatcher;
public class GlobalEventBroadcaster
{
private static var dispatcher:EventDispatcher = new EventDispatcher();
public static function addEventListener(type:String, listener:Function, useCapture:Boolean = false, priority:int = 0, useWeakReference:Boolean = false):void
{
dispatcher.addEventListener(type, listener, useCapture, priority, useWeakReference);
}
public static function removeEventListener(type:String, listener:Function, useCapture:Boolean = false):void
{
if (dispatcher)
dispatcher.removeEventListener(type, listener, useCapture);
}
public static function dispatchEvent(event:Event):void
{
if (dispatcher)
dispatcher.dispatchEvent(event);
}
}
}
That’s it, dispatch and listen to your own Events as you need it. Since this is a very simple approach there is a lot of space for improvements. Just a few ideas:
- Channel support. Could be a huge improvement when you have a lot of listeners already
- Store the current listeners in an array so the removement of all listeners at once for a specific event is possible
- Check if there are listeners for a specific event, if not, do not dispatch the Event since this is ridiculous slow and totally useless
- Remove the possibility for weak references in the addEventListener function. More info on this topic? See Joe Berkovitz’s blog entry why weak references can be dangerous
firstrow RIA e.U.