Thursday, March 06, 2008

Developing Custom Events for FLEX

Ever wondered while coding for events, it would have been great if I had a custom event whose result event target contain what I want , then this is what you should do.

I would make a class called "CustomEvent" extending the "Events" class which will take care of all the custom event details. I also have another class which trigger the events as soon as it get the data from a webservice .

the DataEventHandler class looks something like this

package mypackage{

import mx.collections.ArrayCollection;
import mx.rpc.events.ResultEvent;
import mx.rpc.events.FaultEvent;
import mx.rpc.soap.WebService;
import mx.rpc.soap.LoadEvent;
import mx.controls.Alert;
import flash.events.EventDispatcher;
import flash.events.Event;
import flash.display.Sprite
import components.CustomEvent;

public class DataEventHandler extends Sprite{
private var service_handler:WebService;
private var methodList:ArrayCollection;
private var isLoaded:Boolean = false;

public function startService(path:String):void{
service_handler = new WebService();
service_handler.wsdl= path;
service_handler.loadWSDL();

service_handler.addEventListener(FaultEvent.FAULT,faultHandler);
service_handler.addEventListener(LoadEvent.LOAD,loadHandler);
service_handler.GetOverviewXML.addEventListener(ResultEvent.RESULT,onOverviewResult);
service_handler.GetOverviewXML.addEventListener(FaultEvent.FAULT,faultHandler);
}
private function loadHandler(event:LoadEvent):void {
isLoaded = true;

dispatchEvent(new Event("onLoadService"));
}


private function faultHandler(event:FaultEvent):void {
Alert.show("error :"+event.fault);
}
private function onOverviewResult(r:ResultEvent):void{

dispatchEvent(new CustomEvent("OverviewEvent",r.result));

}
}
The CustomEvent Class looks like this.

package mypackage{


import mx.controls.Alert;
import flash.events.EventDispatcher;
import flash.events.Event;


public class CustomEvent extends Event{


public var itemDescription:*;

public static const OVERVIEW:String ="OverviewEvent"


public function CustomEvent(type:String,description:* ){
super(type,true, true); //bubble by default

itemDescription=description;
}

override public function clone():Event{
return new CustomEvent(type,itemDescription); // bubbling support inside
}



}

}

From the development side I would write

data_handler = new
DataEventHandler();
data_handler.startService("servicepath?wsdl");
data_handler.addEventListener(CustomEvent.OVERVIEW,onOverviewLoad);

private function onOverviewLoad(e:CustomEvent):void{

for(var ns:String in e.itemDescription){
Alert.show(ns+ "::"+e.itemDescription[ns]);
}

}
Note how we included the "CustomEvent" target object. use a for loop to get all the data stored by the result object.Hope rest of the code is self explanatory. This classes has been very useful for me.

No comments: