How to dispatch an event with added data - AS3

user1022521 picture user1022521 · Sep 25, 2012 · Viewed 22k times · Source

Can any one give me a simple example on how to dispatch an event in actionscript3 with an object attached to it, like

dispatchEvent( new Event(GOT_RESULT,result));

Here result is an object that I want to pass along with the event.

Answer

Tomislav Dyulgerov picture Tomislav Dyulgerov · Sep 25, 2012

In case you want to pass an object through an event you should create a custom event. The code should be something like this.

public class MyEvent extends Event
{
    public static const GOT_RESULT:String = "gotResult";

    // this is the object you want to pass through your event.
    public var result:Object;

    public function MyEvent(type:String, result:Object, bubbles:Boolean=false, cancelable:Boolean=false)
    {
        super(type, bubbles, cancelable);
        this.result = result;
    }

    // always create a clone() method for events in case you want to redispatch them.
    public override function clone():Event
    {
        return new MyEvent(type, result, bubbles, cancelable);
    }
}

Then you can use the code above like this:

dispatchEvent(new MyEvent(MyEvent.GOT_RESULT, result));

And you listen for this event where necessary.

addEventListener(MyEvent.GOT_RESULT, myEventHandler);
// more code to follow here...
protected function myEventHandler(event:MyEvent):void
{
    var myResult:Object = event.result; // this is how you use the event's property.
}