9

任何人都可以给我一个简单的例子,说明如何在 actionscript3 中调度一个事件,并附加一个对象,比如

dispatchEvent( new Event(GOT_RESULT,result));

result是我想与事件一起传递的对象。

4

3 回答 3

33

如果您想通过事件传递对象,您应该创建一个自定义事件。代码应该是这样的。

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);
    }
}

然后你可以像这样使用上面的代码:

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

你在必要时收听这个事件。

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.
}
于 2012-09-25T20:08:48.977 回答
3

这篇文章有点旧,但如果它可以帮助某人,你可以像这样使用 DataEvent 类:

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

文档

于 2016-05-04T14:26:24.227 回答
0

如果设计得当,您不必将对象传递给事件。
相反,您应该在调度类上创建一个公共 var。

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.


于 2012-09-25T20:38:20.640 回答