I have an as3 class that I use for communicating with my Zend_AMF endpoint:
package test
{
import flash.events.Event;
import mx.rpc.AbstractOperation;
import mx.rpc.events.ResultEvent;
import mx.rpc.remoting.RemoteObject;
[Bindable]
[RemoteClass(alias="Request")]
public class Request
{
public var url:String = '';
//There are a lot more properties, but I have removed them for brevity
public function Request(url:String){
this.url = url;
}
public function send():void{
//Create the remoting object
var remotingObject:RemoteObject = new RemoteObject('test');
remotingObject.endpoint = "http://site.com/endpoint.php";
remotingObject.showBusyCursor = true;
//Send it
remotingObject.source = this.url;
var op:AbstractOperation = remotingObject.getOperation(null);
op.addEventListener(ResultEvent.RESULT, result);
op.send(this);
}
private function result(event:ResultEvent){
this.dispatchEvent(event);
}
}
}
To use it I do the following:
var request:Request = new Request('someRemotingCommand');
request.addEventListener(ResultEvent.RESULT, catchEvent);
request.send();
public function catchEvent(event:ResultEvent):void{
var result:Response = event.result as Response; //Get result as my response object
trace(result.responseText);
}
All of this works fine, but it takes a lot of work to use it. I always expect a Response object when calling send() on my request.
Ideally I would like to be able to call request.send() and have it return a Response object directly and not having to deal with a listener:
var result:Response = request.send();
Is this possible? If so, how can I go about doing this?
there is a time that elapses or code that needs to complete between an asynchronous event starting and responding.
The as code is not doing anything other that listening for the event to come back, it wouldn’t make sense to hang while it is waiting.
If writing all the extra code is too much work for every event-response pair, create a factory class that will handle event creation and removal that would simplify it to one line, but all you’re doing is hiding the event handlers, which you can’t really avoid when it comes to asynchronous communication.
edit
You could create a class that bundles this into one abstract class, and different classes stemming from this class would handle different commands and responses differently.
the utility of such a setup really depends on what you’re trying to achieve though. With asynchronous calls, it’ll always comes back to event handling.