Tiny, single-purpose class: ResultToFunctionAdaptor

Every now and then I need a small piece of functionality that perfectly fits into a single, minimal-behavior thus single-purpose class. This time I am developping a Adobe Flex application that uses the RemoteObject facilities. Before invoking a method on a RemoteObject, you have to add two event handlers that will be called with a ResultEvent or a FaultEvent respectively. Typically in the “onResult(event:ResultEvent)” function, one takes the result of the event and calls another function or update a view.

In my application, this pattern had been applied at numerous locations until I decided to introduce a simple but effective helper class.  A ResultToFunctionAdaptor is a helper class that has an event handler for a ResultEvent and calls another handler with the result of that event.

public class ResultToFunctionAdaptor
{
	private var _handler:Function;

	public function ResultToFunctionAdaptor(handler:Function) {
			this._handler = handler
	}
	public function onResult(event:ResultEvent):void {
			_handler.call(this,event.result);
	}
}

Using a ResultToFunctionAdaptor I can now encapsulate the event handling and work with Functions only. For example, my (Time)SlotService can be used like this:

...
new SlotService().getAllSlots(fromDate,toDate,showSlots);
...
public function showSlots(slots:Array):void {
    ...
}

and the implementation of SlotService>>getAllSlots(start:Date,stop:Date,callback:Function) contains:

aRemoteObject.getAllSlots.addEventListener("result", new ResultToFunctionAdaptor(callback).onResult);

This class has been added to the Dunelox library which is a collection of ActionScript classes that provides a micro application framework for Adobe Flex applications.

Every now and then I need a small piece of functionality that perfectly fits into a single, minimal-behavior thus single-purpose class.