Creating charts using remote data is as easy as creating dynamic charts. However there is one small catch, it is necessary to synchronize the invoking of the FusionCharts object with the firing of the result event. It must be noted that synchronization is not necessary, If the chart is generated after the firing of the result event. However, if the chart has been generated before the server response, synchronization becomes necessary.
If are wondering why synchronization is needed? Well, it is needed because the methods exposed by the FusionCharts object aren't available until the FCRenderEvent event has fired. The diagram below, illustrates an ideal situation, where the FCSetDataXML method is invoked after the FCRenderEvent event has been fired. In practical cases however, the method may be invoked before the chart has rendered, thereby resulting in failure.
The ideal solution to the problem would be to create the chart dynamically - only after Flex receives the result. This however, is not possible due to architectural constraints. Hence, it is essential to synchronize the two events. Following is the code for synchronizing the two events:
Notice that we have declared a FusionCharts object and a HTTPService object in the code. The HTTPService object is invoked when the creationComplete event of the application is triggered.
<?xml version="1.0" encoding="utf-8"?>
<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml" layout="absolute" xmlns:ns1="com.fusioncharts.components.*"
creationComplete="{service.send()}">
<ns1:FusionCharts id="fc" FCChartType="Column2D" FCRenderEvent="{onRender()}" />
<mx:HTTPService id="service" url="someData.xml" result="{onResult(event)}" resultFormat="xml" />
<mx:Script>
<![CDATA[
import mx.rpc.events.ResultEvent;
private var dataXML:String = "";
private var hasRendered:Boolean = false;
private function onResult(e:ResultEvent):void {
dataXML = e.result.toString();
setData();
}
private function onRender():void {
hasRendered = true;
setData();
}
private function setData():void {
if(hasRendered) {
fc.FCSetDataXML(dataXML);
}
}
]]>
</mx:Script>
</mx:Application>
In the code, the onRender method is called when the FCRenderEvent of the chart is fired. The onRender method sets the hasRendered flag to true and then calls the setData method. Working parallely, the result event of the HTTPService object invokes the onResult method, this method in turn caches the resultant data and then calls the setData method.
The setData method checks whether or not the chart has rendered, prior to setting the data. Thus no matter which event triggers the setData method first, the chart data will always be set to remote data.