How to dispatch an event with added data - AS3

岁酱吖の 提交于 2019-11-27 16:27:04

问题


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.


回答1:


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



回答2:


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




回答3:


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.




来源:https://stackoverflow.com/questions/12590082/how-to-dispatch-an-event-with-added-data-as3

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!