Generic events and additional parameters in Actionscript 3.0?

后端 未结 3 1397
没有蜡笔的小新
没有蜡笔的小新 2021-01-25 18:23

Assuming the following pattern:

someObjectInstance.addEventListener(MyDisplayObject.EVENT_CONSTANT, _handleMyEvent);


private function _handleMyEvent( event:Eve         


        
3条回答
  •  后悔当初
    2021-01-25 19:05

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

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

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

提交回复
热议问题