Flexcomps’s Weblog

Dispatching Custom Events in AS3 with data or object

Posted by: Yogesh Puri on: April 29, 2008

I have been working on a project where we need 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.


23 Responses to "Dispatching Custom Events in AS3 with data or object"

Hi,
Thanks for putting intresting blogs on the site.
It will really help to those people who are migrating from AS2 to AS3. Good job buddy.

Regards
Faiz

It is really great sir

Devendra ibn7

but still having some problem i want to send custom event like array of object on button click but i follow your rule but still having some problem

package {
import flash.events.*;
import flash.net.URLRequest;
import flash.display.Loader;
import flash.display.Sprite;
public class imageLoader extends EventDispatcher {
private var _mc:Sprite;
private var url:String;
private var loader:Loader;

public function imageLoader(_mc:Sprite, url:String) {
this._mc = _mc;
this.url = url;
loadImg();
_mc.addChild(loader);
}
private function loadImg():void {
loader = new Loader();
loader.contentLoaderInfo.addEventListener(Event.COMPLETE, onComplete);
loader.contentLoaderInfo.addEventListener(IOErrorEvent.IO_ERROR, onIOError);
var request:URLRequest = new URLRequest(url);
loader.load(request);
}
private function onComplete(event:Event):void {
dispatchEvent(new Event(“onImageLoad”));
}
private function onIOError(event:IOErrorEvent):void {
trace(“IO Error.”);
}
}
}

////////////////////////////////////////////////

var myImageLoader:imageLoader = new imageLoader(this, “http://static.ibnlive.com/pix/homepageimages/ftn_jn20.jpg”);
myImageLoader.addEventListener(“onImageLoad”, callbackHandler);
function callbackHandler(event:Event) {
trace(“Image Loading Complete!”);

}
i am getting event but i want some more parameter like i want to send array with my event . So should i have to use custom event for same if you can give me complete solution pls provide us
//////////////////////////////////////////////

[...] one integer and one string. The incomingJS function then put’s those two arguments into an event (here’s a tutorial if you’ve never made custom events) and dispatches it, and then returns ‘true’ to JS – we now [...]

Hey, did you go to GW in Denver? I remember a math teacher talking about such a Yogesh.

Thanks

To clear me up the custom events, can you help us more regarding the “(type:String, bubbles:Boolean = false, cancelable:Boolean = false)”

these three parameter in event with example.

And can you explain Event.preventDefault(), how can be an event cancel, like to cancel the event of display text in text field when input the value

I search a lot but found nothing.

thanks in advanced.

Regards

vivek.

thank u very much for the information . I hesitated to migrate from AS2 to AS3.
I have tried to create a new event and the code.
Amazing i succeeded to make my sample work.
keep up your good work
I will be a regular reader of ur blog

Thanks a lot. Much helpful.

Any way to get an as3 and fla file. No worries if not, but I’m a noob bangin’ my head trying to get a hold of all of these concepts.

did not work for me
I think I’m using it wrong
do I need to make instance of the class at the 2 other classes
what should I do to send a value with the action
godfather I don’t know what to do
I don’t know what to do

This works really well for me, been looking for a nice solution to pass on data with the eventdispatcher for a while. Thanks.

just curious, in this example, who is doing the dispatching?

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

good example, works perfectly fine. though not everything one need to do is explained here. so m adding stuff to it to help out.
steps are:
1. add custom class
2. add event to your component [Event(name=ChapterCustomEvent.ONSELECT, type=myprojectname.events.ChapterCustomEvent", bubbles=true)]
3. add handler in parent this.childComponent.addListner(ChapterCustomEvent.ONSELECT, handlerMethodName)
4. fire event from your component dispatchevent (new ChapterCustomEvent(ChapterCustomEvent.ONSELECT,”THIS IS STRING DATA, PARENT SHOULD KNOW WHAT IT IS EXPECTING HERE”));

=D,

Even though i didn’t read all of it, because i knew how to dispatch events, I was clueless on the Bubble set to false as default…even though FlashDevelop shows it right there in my face.

Thanks =)
Keep up the good work.

Thanks a lot.

It’s really helpful ;-)

Thx ☺♥

Thanks buddy very nice and effective tutorial also simple to understand..

I am having some prob. don’t knw whats happening. i did all like normal class writing and when i run i got error : ReferenceError: Error #1065: Variable FlashmadEvent is not defined.
at djName/clicked()

just do like this very simple:
stage.addEventListener(MouseEvent.CLICK, do1, false, 0, true);
function do1(evt:MouseEvent){do2(evt, “Shift key was down:”)}
function do2(evt:MouseEvent, msg:String) {
trace(msg, evt.shiftKey);
trace(“”);
trace(evt);
}

Nice post. very informatic with short and simple way.

Nice example thanks. I am just curious about something…
What happend with args:

bubbles:Boolean = false, cancelable:Boolean = false

because you only call
super(type);

that mean that you lost Evnet features that controls bubbling, and canceling.. you redirect other args something as :

super(type, bubbles, cancelable);

Am i right or i lost something.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Connecting to %s

 

April 2008
M T W T F S S
    May »
 123456
78910111213
14151617181920
21222324252627
282930  

Blog Stats

  • 313,082 hits
Follow

Get every new post delivered to your Inbox.