Support for the Command pattern

Swiz supports the use of the Command pattern with the CommandMap class, which you then register as a bean. The first step is to extend CommandMap and override the mapCommands() method. Inside the method you make individual calls to mapCommand(), which maps an event to a command class. In the example below, the first two arguments are pretty self explanatory. They are the event type and the command you want to be triggered by that type. The third and fourth arguments are optional, but can be very useful.

The third argument is the event class associated with the event type, and when provided allows Swiz to prevent event type collisions. What this means is that if MyEvent.OPEN and YourEvent.OPEN both evaluate to "open", providing MyEvent as the third argument will instruct Swiz to only execute MyCommand in response to MyEvent.OPEN. This argument is optional but recommended.

The fourth argument is oneTime:Boolean = false. If you set this argument to true, Swiz will remove the mapping after the first time the command is executed. This can be useful for activities you know will only happen once, like configuration loading or other bootstrapping activities.

public class MyCommandMap extends CommandMap
{
	override protected function mapCommands() : void
	{
		mapCommand( MyEvent.OPEN, MyCommand, MyEvent, false );
	}
}


Finally, add your CommandMap to one of your BeanProviders. It is not necessary to register your Command classes as beans. Their presence in the mappings is all the information Swiz needs.

<swiz:BeanProvider>
	<command:MyCommandMap id="myCommandMap" />
</swiz:BeanProvider>


The commands you register must implement one of two interfaces provided by Swiz. ICommand is the base interface, simply defining an execute() method.

public interface ICommand
{
	function execute():void;
}


If your Command needs access to the event that triggered it, simply implement IEventAwareCommand. Notice IEventAwareCommand extends ICommand.

public interface IEventAwareCommand extends ICommand
{
	function set event( value:Event ):void;
}


As always, make sure you've added the correct event package containing your event to the Swiz eventPackages array and that's all there is to it. Any time Swiz handles an event, the associated command(s) will be executed.