AS3 – messaging between objects, a decoupled approach

I’m working on an interactive installation. I’m building a couple of AIR apps. A really useful object that I’ve worked with in the past is a Broadcaster. Think of it as the telephone operator of old…you know the kind at a switchboard that actually has to connect a wire between the two callers. Well, the Broadcaster is great for keeping objects decoupled from each other. Typically if you want to send message between objects, each object has to somehow know the existence of the other object. You do this by keeping a reference to it.

//This is inside the sender class
// save a reference to the receiver
// so we can tell it to do something later
var receiver;
receiver = {the_receiver_object};

With the Broadcaster class, you just tell the Broadcaster that you’re interested in a certain message. Any object in your application can fire that message. Once that is fired, you get an event and it’s up to your class to handle it.

// in the receiver class
// when we receive the "RESET" message,
// run the reset_activity() function.
Broadcaster.subscribe( "RESET", this.reset_activity );

function reset_activity ( e:RichEvent ) {
//do something

// in the sender class
// fire off the "RESET" message
// and also pass along some parameters "RESET" , {transition:"fade_out"} );


Notice that neither class has any knowledge of the other class. They are really just ‘connected’ by the message that they are firing and listening to.

The beauty of this is that any class can fire a message and any class can listen(subscribe) to that message. The Broadcaster does the routing between sender and receiver just like the old telephone switchboard days!

Here’s the awesome minair library that has the Broadcaster class. If you just want to use this messaging architecture you’ll need to grab the Broadcaster, RichEvent, and the Log classes. Good luck!

Leave a Reply