如何使用添加的数据调度事件 - AS3

时间:2012-09-25 19:51:29

标签: actionscript-3 flash flex events dispatchevent

任何人都可以给我一个简单的例子,告诉我如何在actionscript3中发送一个附加了对象的事件,比如

dispatchEvent( new Event(GOT_RESULT,result));

此处result是我想要传递事件的对象。

3 个答案:

答案 0 :(得分:30)

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

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

答案 1 :(得分:3)

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

ORKLineGraphChartView

MaxU

答案 2 :(得分:0)

如果设计得当,您不应该将对象传递给事件 相反,你应该在调度类上创建一个public 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.