一般事件和其他参数在ActionScript 3.0? [英] Generic events and additional parameters in Actionscript 3.0?
问题描述
假设下面的模式:
someObjectInstance.addEventListener(MyDisplayObject.EVENT_CONSTANT, _handleMyEvent);
private function _handleMyEvent( event:Event = null ):void
{
// Event handler logic...
}
如果我想所需的参数添加到处理函数我能够做到这一点,仍然使用通用事件和事件监听器?还是我正确的假设,我需要创建一个具有通过传递到处理函数的事件对象在它的参数和参考的自定义事件类?
If I wanted to add a required parameter to the handler function am I able to do this and still use a "generic" event and event listener? Or am I correct in assuming that I need to create a custom event class that has the parameter in it and reference that through the event object passed into the handler function?
要短语这个法子......如果我有一个处理函数,看起来像这样:
To phrase this another way... If I have a handler function that looks like this:
private function _handleMyEvent( data:Object, event:Event = null ):void
{
if (data == null)
{
return;
}
// Event handler logic...
}
那么,什么是的addEventListener功能需要什么样子的?有没有更高级的语法?有没有办法来带密封盖做到这一点?
Then what does the addEventListener function need to look like? Is there a more advanced syntax? Is there a way to do this with closures?
寻找一个明确的code的例子和/或文档的参考。只是想了解,如果我绝对要覆盖一般事件类在这种情况下。
Looking for a clear code example and/or documentation reference. Just trying to understand if I absolutely have to override the generic Event class in this scenario.
推荐答案
如果你需要自定义数据与您的活动行程,是的,你需要创建一个自定义事件类。
If you need custom data to travel with your event, yes, you need to create a custom event class.
下面是一个简单的例子:
Here's a simple example:
package {
import flash.events.Event;
public class ColorEvent extends Event {
public static const CHANGE_COLOR:String = "ChangeColorEvent";
public var color:uint;
public function ColorEvent(type:String, color:uint, bubbles:Boolean = false, cancelable:Boolean = false) {
this.color = color;
super(type, bubbles, cancelable);
}
override public function clone():Event {
return new ColorEvent(type, color, bubbles, cancelable);
}
}
}
请注意,clone方法是不可选的。您必须使用此方法,您的自定义类的事件,永远不会再正常播出(比如说当一个对象获取事件,然后再重新调度它,因为它是自己的)。
Please note that the clone method is NOT optional. You must have this method in your custom class for your event to ever be re-broadcast properly (say when one object gets the event, and then re-dispatches it as it's own).
现在,作为调度的情况下,将这样的工作(这显然code会去在扩展EventDispatcher类的方法)。
Now as for dispatching the event, that would work like this (obviously this code would go in a method of class that extends EventDispatcher).
dispatchEvent(new ColorEvent(ColorEvent.CHANGE_COLOR, 0xFF0000));
最后,订阅事件:
And finally, to subscribe to the event:
function onChangeColor(event:ColorEvent):void {
trace(event.color);
}
foo.addEventListener(ColorEvent.CHANGE_COLOR, onChangeColor);
这篇关于一般事件和其他参数在ActionScript 3.0?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!