Passing parameters to event listeners / handlers

前端 未结 8 1360
清酒与你
清酒与你 2020-12-06 06:40

How do you pass parameters / variables through event listeners? I\'ve overcome this problem fairly effectively using anonymous functions; which is an incredibly simple solut

8条回答
  •  孤城傲影
    2020-12-06 07:08

    It is probably better practice to make a custom class that extends MovieClip for your thumnbnail, and have that thumbnail dispatch a custom Event class that has a place to store your data:

    Make a custom URLEvent that can store the url property along with the event

    package{
    
    import flash.events.Event;
    
    public class URLEvent extends Event{
    
        public var url:String;
        public static const CLICK:String = "URLEventClick"
    
        public function URLEvent(type:String, url:String = "", bubbles:Boolean = false, cancelable:Boolean=false){
            super(type, bubbles, cancelable);
            this.url = url;
        }
    
        override public function clone():Event{
            return new URLEvent(type,url,bubbles,cancelable);
        }
      }
    }
    

    Make a custom thumbnail class that can store the url variable, and sends a URLEvent when clicked:

    package{
    
    import flash.display.MovieClip;
    import flash.events.MouseEvent;
    
    public class Thumbnail extends MovieClip{
    
        protected var url:String;
    
        public function Thumbnail(url:String){
            this.url = url;
            addEventListener(MouseEvent.CLICK,clickHandler);
        }
    
        //the thumbnail captures its own click and dispatches a custom event
        protected function clickHandler(event:MouseEvent):void{
            dispatchEvent(new URLEvent(URLEvent.CLICK,url));
        }
    
    }
    

    Now you can use your Thumbnail class to load each image:

    tempThumb.addEventListener(URLEvent.CLICK,tempThumbClickHandler);
    
    function tempThumbClickHandler(event:URLEvent):void{
    //we can get the url property direct from the URLEvent
        loadImage(event.url);
    }
    

    This method is much better OOP practice, as you do not need to know what type of object your event.target is - you know from the event type exactly what type of data will be sent with each event.

提交回复
热议问题