Message Relay is a small utility for ActionScript3 used to avoid the complex code spaghetti associated with direct object references. Message Relay works by using runtime listeners. This is quite a bit like using regular Flash events, but instead of relying on direct listener references or event propagation, Message Relay uses a central relay object. All Message Relay messages have a topic that identifies the messages. Any object can register to listen to messages with a given topic, and the relay broadcasts the messages to all registered listeners.
You can read more about the general idea of messaging on Wikipedia.
Download
- Download Message Relay – updated May 25, 2009
Usage example
Main.as:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 | package com.nnyman.examples
{
import com.nnyman.util.Message;
import com.nnyman.util.MessageRelay;
import com.nnyman.util.MessageRelayListener;
/**
* Main class listens to messages on topic Example.INITIALIZED
*/
public class Main implements MessageRelayListener
{
public function Main()
{
// Register a listener for topic Example.INITIALIZED
MessageRelay.addListener(this, Example.INITIALIZED);
}
/**
* This method is required by the MessageRelayListener interface.
* Messages broadcast by MessageRelay are handled by this method.
*/
public function receiveMessage(message:Message):void
{
if (message.getTopic() == Example.INITIALIZED)
{
trace("Message from " +
message.getSender() +
" with data " +
message.getData());
}
}
}
} |
Example.as:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 | package com.nnyman.examples
{
import com.nnyman.util.Message;
import com.nnyman.util.MessageRelay;
/**
* Example class sends a single message.
*/
public class Example
{
// Message Relay topic
public static const INITIALIZED:String = "example initialized";
public function Example()
{
// Send message with topic INITIALIZED, a data String,
// and 'this' as the sender. You can use any object for data.
MessageRelay.sendMessage(new Message(INITIALIZED, "my data", this));
}
}
} |
Flash Events compared to Message Relay
When registering an event listener, you need to have direct reference to both the object sending events, and the object listening to the events:
1 | senderObject.addEventListener(MouseEvent.ROLL_OVER, listenerObject.rollOverHandler); |
With Message Relay, the sender and the listener are decoupled, and no direct references are needed. In fact, the sender and the listener can be completely unaware of each other.
Sending a message:
1 | MessageRelay.sendMessage(new Message("demo message", null, senderObject)); |
Listening to a message:
1 | MessageRelay.addListener(listenerObject, "demo message"); |
