Question

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.

Was it helpful?

Solution

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.
}

OTHER TIPS

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

If designed properly you shouldn't have to pass an object to the event.
Instead you should make a public var on the dispatching class.

public var myObject:Object;

// before you dispatch the event assign the object to your class var
myObject = ....// whatever it is your want to pass
// When you dispatch an event you can do it with already created events or like Tomislav wrote and create a custom class.

// in the call back just use currentTarget
public function myCallBackFunction(event:Event):void{

  // typecast the event target object
  var myClass:myClassThatDispatchedtheEvent = event.currentTarget as myClassThatDispatchedtheEvent 
  trace( myClass.myObject )// the object or var you want from the dispatching class.


Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top