可以dispatchEvent()的携带AS3参数呢?参数、dispatchEvent

2023-09-08 13:13:19 作者:你不配拥有我

你们看这个例子:

addEventListener("myEventType", myFunction("argument"));

function myFunction(args:String):Function {
    return function(evt:Event):void {
        trace(evt.currentTarget, "has", args);
    };
}

dispatchEvent(new Event("myEventType", true));

它的工作原理。

It works.

我可以做同样的事情,但通过参数则dispatchEvent()

Can I do something similar, but passing "argument" through dispatchEvent()?

这将会是非常方便的在一个情况下则dispatchEvent()是一个完全分离的类从的addEventListener() myFunction的()

It'd be very handy in a situation where dispatchEvent() is in a wholly separated class from addEventListener() and myFunction().

我会在这个需要很多,所以我想这样做,不为任何情况下创建自定义事件类。

I'll be needing this a lot, so I want to do it without creating a custom event class for every situation.

推荐答案

您可以使用本机 flash.events.DataEvent 传递字符串参数,或者创建自定义的 DataEvent 数据:* 在你需要传递参数的所有情况财产到事件处理程序。

You can use native flash.events.DataEvent for passing String parameter or create custom DataEvent with data:* property in all situations where you need to pass parameters to event handler.

如果你想在添加事件监听器,你可以创建监听器​​对象持这种自定义参数(但我认为这项技术比自定义事件更复杂)的地方自定义事件监听器的行为: 的addEventListener(myEventType,新的事件监听器(参数1)的onEvent。); ,其中事件监听器是这样的类这样的:

If you want to customize the behavior of event listener in the place of adding event listener you can create "listener" object for holding this custom parameters (but I think this technique is more complicated than custom events): addEventListener("myEventType", new EventListener("param1").onEvent);, whereEventListener is the class like this:

public class EventListener
{
    private var params:*;

    public function EventListener(params:*)
    {
            this.params = params;
    }

    public function onEvent(event:Event):void
    {
            trace("onEvent, params = ", params);
    }
}