GenericActionMock.as

package
{
	import flash.events.EventDispatcher;
	import flash.events.TimerEvent;
	import flash.utils.Dictionary;
	import flash.utils.Timer;

	import mx.core.mx_internal;
	import mx.messaging.events.MessageEvent;
	import mx.messaging.messages.AsyncMessage;
	import mx.rpc.AsyncToken;
	import mx.rpc.Fault;
	import mx.rpc.events.FaultEvent;
	import mx.rpc.events.ResultEvent;

	public class GenericActionMock extends EventDispatcher
	{
		private var calls:Dictionary = new Dictionary();

		protected var _flag:Boolean;

		public function GenericActionMock(wantGoodResult:Boolean = true)
		{
			_flag = wantGoodResult;
		}

		protected function sendAsyncToken(token:AsyncToken, delayMs:int = 1000) : void
		{
			var timer:Timer = new Timer( delayMs, 1 );
			if(_flag)
				timer.addEventListener( TimerEvent.TIMER, sendMockResult );
			else
				timer.addEventListener( TimerEvent.TIMER, sendMockFault );

			timer.start();

			calls[ timer ] = token;
		}

		protected function sendMockResult( event:TimerEvent ):void
		{
			var timer:Timer = Timer( event.target );
			timer.removeEventListener( TimerEvent.TIMER, sendMockResult );

			var token:AsyncToken = AsyncToken( calls[ timer ] );
			delete calls[ timer ];

			var mockData:Object = ( token.data ) ? token.data : new Object();
			token.mx_internal::applyResult(ResultEvent.createEvent(mockData, token));

			timer = null;
		}

		private function sendMockFault( event:TimerEvent ):void
		{
			var timer:Timer = Timer( event.target );
			timer.removeEventListener( TimerEvent.TIMER, sendMockFault );

			var token:AsyncToken = calls[ timer ];
			delete calls[ timer ];

			var fault:Fault = new Fault("Mock Fault Code", "Mock Fault String");
			fault.message = "Error on server side, attempting to getAll/save/update/remove";
			token.mx_internal::applyFault(FaultEvent.createEvent(fault, token));

			timer = null;
		}

		protected function fireMessage(object:Object) : void
		{
			var msg:AsyncMessage = new AsyncMessage(object);
			dispatchEvent(new MessageEvent(MessageEvent.MESSAGE,true,false,msg));
		}
	}
}

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s