Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to dispatch an event with added data - AS3

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.

like image 549
user1022521 Avatar asked Sep 25 '12 19:09

user1022521


2 Answers

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.
}
like image 105
Tomislav Dyulgerov Avatar answered Oct 20 '22 00:10

Tomislav Dyulgerov


This post is a little old but if it can help someone, you can use DataEvent class like so:

dispatchEvent(new DataEvent(YOUR_EVENT_ID, true, false, data));

Documentation

like image 32
g0tcha- Avatar answered Oct 19 '22 23:10

g0tcha-