Dispatching Custom Events in AS3 with data or object

detail here
to send custom information or data to the listener object when a custom Event is going to be dispatched. So here is what i have done to achieve the same

The flash new Event mechanism provides you a facility to create a new event and the default constructor call is something like this

Event(type:String, bubbles:Boolean = false, cancelable:Boolean = false)

so there is no by default parameter to send information across the dispatcher and listener objects ( Other than using event.target.*** method on listener end).

Following is the code i have done for overcome this

Create a CustomEvent.as Class as following

package eventsSystem {
import flash.events.Event;

public class CustomEvent extends Event {
public static const ONLOADED:String = “OnLoaded”;
//———– Define your custom Event string constant

public var data:*;
//————- Define a data variable of * type to hold any kind of data object


//———— Constructor
public function CustomEvent(type:String, data:*){
this.data= data;
super(type);
}
}
}

Now what we have done here is to create a new CustomEvent class that is extended from flash.events.Event class and have put a variable to hold information we want to send to listeners called “data”. We have kept data of * type so that it can take any kind of information

Now call Super(type) to register it with Events system

Now you need to use the following to dispatch events using CustomEvent

dispatchEvent(new CustomEvent(CustomEvent.ONLOADED, data ));

on The listener end you can use it like this

_loaderObj.addEventListener(CustomEvent.ONLOADED,setXML,false,0,true);
// To register your object to listen to custom event

//——— Method invoked after custom event is listened ————

private function setXML(evt:CustomEvent):void{
var _XML:XML = new XML(evt.data);
}

So now you can directly pass your data along with the custom Events.

Nhận xét

Bài đăng phổ biến từ blog này

Ký tự viết tắt trong chat & email

dung lượng RAM lớn nhất mà HĐH cấu trúc 32-bit nhận được

Ubuntu LAMP Server