Flash CentralDispatcher

Tagged as: Flash

A few recent AS 2.0 projects have drawn the need for a sort of global event messaging system for Flash. Purists may say that's lazy or confusing, 'what if someone else needs to edit your code?' I don't care I tell them! I kid, I kid... I do care, but it is a rare occurrence when someone needs to edit my code and this is why I document and comment as much as possible. Also these projects are usually quick turn arounds and border on 1-offs.

Back to the subject at hand. CentralDispatcher allows me to listen and send events from objects without explicitly having those objects know who the other is. But why? I hate manually bubbling, there may be better ways, but if i have views which have views that all need to broadcast events to the controller I don't want to manually bubble all the way up the chain to get those events in the hands of the controller. Also it seems messy and i'm doubling my method calls.

So how does this work? Mind you, this is not feature complete but it works for me and that's what's most important here.

Let's say I have a class that loads a data file, let's call it ClassB. My Controller wants to know when that file was loaded and it wants to receive that data, let's call him ClassA. Here's how it would look:

Class A:

import com.hybrid.events.CentralDispatcher;
 
class ClassA {
 
function ClassA(){
CentralDispatcher.addEvent( "onGetFile", this );
}
 
private function onGetFile( evt:Object ):Void {
trace("Stuff : "+evt.data );
}
}

Class B:

import com.hybrid.events.CentralDispatcher;
 
class ClassB {
 
function ClassB(){
CentralDispatcher.sendEvent( { type:"onGetFile", data:"stuff" } );
}
}

addEvent returns a Boolean which will tell you whether or not your event has been set. This can be helpful if you have already set this event so your not getting double the callbacks.

Event Queue. What if you were to prematurely fire an event but didn't have your listener setup yet? If you fire an event and there is no listener of type for that event it gets queue'd and fired when the listener gets set. Why would you ever do this?
What if, for example, a MovieClip has been attached to the stage, in it's onLoad handler you want to broadcast that message of "loaded" so anyone that needs it or may need it in an up and coming event can know it's ready to go without having to check it or call a method on it to make sure it's readily available. Thin?

As always it's good to clean up your events, here you simply use removeEvent:

CentralDispatcher.removeEvent( "onGetFile", this );

Removing all events by type. If you have multiple listeners all listening for a specific type, you can remove them all at once using:

CentralDispatcher.removeEventsByType( "onGetFile" );

Well that's about it. It's not rocket science but it's come in very handy for me on more than one occasion.

Download CentralDispatcher