2010-08-12

RemoteService

Recently I was working on some projects using Flex and PureMVC. It's wonderful when using PureMVC to build a Flex application. It makes things easier!!

Here is an example that using Remoting with PureMVC. In this demo, it uses a Delegate class to call the remote methods, and the Proxy class calls the Delegate class method to get data. As you can see, there are two same methods in two classes, and all methods in the Delegate class are almost the same, except there are different method names and different parameters.

It's good to use Delegate class when one day you want to change the way you get data, using WebService instead of RemoteObject, for example. It is easier to make changes.

But it still bothers me.

So I created my own class to make using RemoteObject easier.

Below is the code:

package cc.hayama.services {
import mx.rpc.remoting.mxml.RemoteObject;
import mx.rpc.remoting.Operation;
import mx.rpc.IResponder;
import mx.rpc.AsyncToken;

public class RemoteService {

private var service:RemoteObject;

public function RemoteService(destination:String):void {       
this.service = new RemoteObject();
this.service.showBusyCursor = true;
this.service.destination = destination;      
}

public function set endpoint(value:String):void { service.endpoint = value;}
public function get endpoint():String { return service.endpoint; }

public function set source(value:String):void { service.source = value; }
public function get source():String { return service.source; }

public function call(responder:IResponder, methodName:String, ...args):void {
var token:AsyncToken;
var op:Operation;

op = service.getOperation(methodName) as Operation;
op.arguments = args;

token = op.send();
token.addResponder(responder);
}
}
}

And you can use it like this:
private function onHelloReslut(event:ResultEvent):void {
...
}
private function onFault(event:FaultEvent):void {
...
}
var service:RemoteService = new RemoteService("test");
service.source = "Hello";
service.call(new mx.rpc.Responder(onHelloResult, onFault), "say", "hello");

The point is that I used a "...args" parameter in call method.

With this **magic** parameter, I can call the remote method and pass any numbers and any types of parameters, using just one call method!!