Home > Flex > Placing Cairngorm Commands inside Modules

Placing Cairngorm Commands inside Modules

In order to reduce the size of the main application SWF, I have come up with some practices to keep as much code as possible in the module while still utilizing a single event dispatcher and service locator.

I accomplished this by creating a Cairngorm command to register other commands found inside modules.

First I define a CommandReference ValueObject:

package net.huyler.UserManager.vo
{
	import com.adobe.cairngorm.vo.ValueObject;

	[Bindable]
	public class CommandReference implements ValueObject
	{
		public var event:String;
		public var func:Class;
	}
}

Next I define a RegisterEvent which will be dispatched for each command I need to register:

package net.huyler.UserManager.events
{
    import com.adobe.cairngorm.control.CairngormEvent;
    import net.huyler.UserManager.vo.CommandReference;

    public class RegisterCommandEvent extends CairngormEvent
    {
    	public static const EVENT_REGISTER_COMMAND:String
		= "registerCommandEvent";

        public var command : CommandReference;

        public function RegisterCommandEvent(
		cmd:CommandReference )
        {
            super( EVENT_REGISTER_COMMAND );
            command = cmd;
        }
    }
}

Then I define the RegisterCommand which will field the RegisterEvent Events:

package net.huyler.UserManager.command
{
    import mx.core.Application;
    import com.adobe.cairngorm.commands.Command;
    import com.adobe.cairngorm.control.CairngormEvent;
    import net.huyler.UserManager.events.RegisterCommandEvent;

    public class RegisterCommand implements Command
    {
	public function execute( event : CairngormEvent ) : void
	{
	    Application.application.controller.addCommand(
		RegisterCommandEvent(event).command.event,
		RegisterCommandEvent(event).command.func);
	}
    }
}

From the module, I dispatch a RegisterEvent for each command I want to register. This gets called when the module is initialized:

private function onInitialize():void
{
	var command:CommandReference = new CommandReference();
	command.event = EmployeeEvent.EVENT_EMPLOYEE;
	command.func = EmployeeCommand;

	// Register event and command with Cairngorm
	CairngormEventDispatcher.getInstance().dispatchEvent(
		new RegisterCommandEvent( command )
 );

}

And that’s it! Since the command class is never referenced inside the main application, its code doesn’t get pulled in. You can also break out delegate classes this way also. As the size and number of commands grows in each of your modules you can rest easy knowing the initial download of your application will not increase.

Categories: Flex Tags:
  1. No comments yet.
  1. No trackbacks yet.
You must be logged in to post a comment.