Flex RemoteObject - handling multiple requests

SkippyFlipjack picture SkippyFlipjack · Jul 12, 2009 · Viewed 10.4k times · Source

I have a couple of remote object methods that I want to respond to in different ways depending on the context, but I'd rather not set up a bunch of different RemoteObject aliases. Any advice on doing that? Some background:

Let's say I have an admin application that displays sales stats in different ways. The remote method looks like:

<mx:RemoteObject id="rpt" destination="AMFServer">
  <mx:method name="getSalesStats" fault="getSalesStatsFault(event)" 
    result = "getSalesStatsSuccess(event)" />
</mx:RemoteObject>

The getSalesStats method takes an employee ID and a sales type as its arguments. You'd call it like:

rpt.getSalesStats(120, "peanuts");

public function getSalesStatsSuccess(e:ResultEvent):void {
   salesdata:ArrayCollection = e.result.rows as ArrayCollection; 
   salesGraph.dataProvider = salesdata; 
   salesGraphPanel.title = "Peanut Sales, 1990";
}

I want to be able to call this method in different contexts, sometimes sending the result to a chart and sometimes to a datagrid; I want to be able to change the title and type of chart depending on what the user wants. Some of what I want can be achieved by evaluating the data returned from the server; the object contains the report name, so I can evaluate that value. But some things need to change based on more than just what I get back from the server. If this was a synchronous call, it would be easy; I'd do something like:

function buttonOneClick():void {
   myData1:ArrayCollection = getSalesStats(120, "peanuts");
   myChart.dataProvider = myData1;
}

function buttonTwoClick():void {
   myData2:ArrayCollection = getSalesStats(120, "cashews");
   myDataGrid.dataProvider = myData2; 
}

I'd like to pass something through the remote method to the responding function, like:

rpt.getSalesStats(120, "peanuts", "clicked button one");

but that of course throws an error because the server doesn't want that last argument. Any thoughts? I'll clarify if this is confusing..

Answer

Joel Hooks picture Joel Hooks · Sep 2, 2009

Here is a great example of using AsyncToken with RemoteObject method calls to do precisely what you need.

Something to keep in mind when you are using AsyncToken is that it is a dynamic object and you can add any property you'd like to it. The event in your responder method will carry a reference to the AsyncToken and you can access your dynamic properties to easily identify the context of the response.