Message Exchanging Using AS3-Signals

Written by

Decide what you want, decide what you are willing to exchange for it. Establish your priorities and go to work.

H. L. Hunt

One question I see quite a lot when it comes to architecting an application using MVC is how to get data into the view from the model and keeping that data current. The simplest and quickest routes to achieve this is to create a reference to the model within a view mediator and either bind or directly get the data. This is an approach I indeed blogged about but is a technique I quickly moved away from. Here is how I now manage this.

I am a staunch advocate of AS3-Signals and use them extensively in all my applications nowadays. Whilst contemplating how to best manage data within an modular application that was rapidly growing it was Stray as usual, who pointed me to a technique that I use consistently now due to its simplicity, cleanliness and strong typing the response Signal and payload.

A suggested simple example could be a view mediator has been registered after a user logs in and the view wants to display the name of the currently logged in user which is stored in the model . Using AS3-Signals a request-response approach can be used where the mediator can dispatch a request Signal for the username within the onRegister() method (if using robotlegs), then a command can retrieve the data from the model and dispatch a Signal response with the username.

Example in a Robotlegs application scenario:

The first key factor to this logic is the requesting Signal needs to create and pass as a payload the response Signal. This can simply be a plain ol’ Signal or a custom Signal you have created.

1
2
3
4
5
6
7
8
9
public function RequestSignal()
{
    super(ResponseSignal);
}

public function createResponse():ResponseSignal
{
    return new ResponseSignal(String);
}

As you can see the ResponseSignal is expecting to pass a String value as its payload.

The Mediator would dispatch the injected instance of the RequestSignal with the response Signal as the payload. A handler method will need to be setup for the response.

1
2
3
4
5
6
7
8
9
10
11
public function submitRequest():void
{
    var response:ResponseSignal=requestSignal.createResponse();
    response.addOnce(onResponse);
    requestSignal.dispatch(response);
}

public function onResponse(username:String):void
{
    view.username=username;
}

And finally a command would be mapped to the RequestSignal to manage the retrieving of the model data and dispatching of the response Signal.

1
2
3
4
5
6
7
[Inject]
public var responseSignal:ResponseSignal;

override public function execute():void
{
    responseSignal.dispatch(model.username);
}

Full example application code can be found here on github

I have found this to be a really nice standardised approach to exchanging messages throughout my applications, thanks once again to Stray and Rob Penner.

Comments