Quality Reads

Tuesday, June 24, 2008

Using DI to add a PureMVC Mediator in Flex

Classic issue with PureMVC, how do you add your mediators to your Flex components in an application at initialization. If you're not concerned with tight coupling you might add all the mediators with one command. But what if you don't want to tie all the mediator initialization together in one command? You might be thinking make separate commands for each mediator and fire it off as a PureMVC MacroCommand. Not a bad idea. It would certainly get the job done. But what about reusing the same command for each component and dependency injecting the mediator class and view component reference? Oh so clean. I love it and I think you will to.


//inside command class
public var mediatorClass:Class;
public var viewLocation:String;

override public function execute( note:INotification ):void
{
var m:IMediator = new mediatorClass() as IMediator;
m.viewComponent = getViewComponent( note.getBody() );
Facade.getInstance().registerMediator( m );
}

protected function getViewComponent( app:Object ):Object
{
var result:Object = app;
for each( var subItem:Object in viewLocation.split(".") )
{
result = result[subItem];
}
return result;
}

The viewLocation would be equal to a String like "someComponent.menu.list" where someComponent is located directly under the main application and menu is a subcomponent of that etc. etc.

If you don't know how to handle DI in a Flex application, I highly suggest you take a look at the Prana Framework. Its made a huge difference in the flexibility and extensibility of the Flex product I'm currently working on. Plus, you'll be able to handle mediator initialization in seconds with one class. :)

Cheers,
Todd

No comments: