October 2007 Archives

Hooking dispatchEvent for Cairngorm Events

| No Comments | No TrackBacks

Gone are the days of cairngormEvent.dispatch(); and CairngormEventDispatcher.getInstance().dispatchEvent( cairngormEvent );. Say hello to dispatchEvent( cairngormEvent );!

A downside of using Cairngorm is that you need to remember that Cairngorm events are "special". Because of how the controller registers listeners, you need to dispatch Cairngorm events through the CairngormEventDispatcher instance in order for the associated commands to execute. Self-dispatching events were added in Cairngorm 2.2 to make things a little easier, but that addition still doesn't address the fact that these events are "different" from other events:

public function doLogin():void
{
	var event:LoginEvent = new LoginEvent( username.text, password.text );
	// Dispatch through the dispatcher directly
	CairngormEventDispatcher.getInstance().dispatchEvent( event );
	// Or, have the event dispatch itself using Cairngorm 2.2+
	event.dispatch();
}

A better approach, I think, is to remove the "special"-ness of Cairngorm events and treat them the same as any other regular event. Rather than having to remember that Cairngorm events get dispatched a special way, doesn't it make sense to simply use the standard dispatchEvent function?

In order to accomplish this, we need to abstract the Cairngorm event dispatching logic further up the chain. We still need to to dispatch Cairngorm events through the CairngormEventDispatcher instance, but we can create an abstraction that allows us to not have to know this extra information. This abstraction allows us to treat Cairngorm events as regular events and just dispatchEvent() them.

So how do we create this abstraction? Simple. We hook dispatchEvent at the UIComponent level. Example code after the jump.

Flex.org - The Directory for Flex

Archives