Passing parameters to event listeners / handlers

前端 未结 8 1323
清酒与你
清酒与你 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:09

    You can do the following, which basically is a cleaner way of passing custom data.

    example code:
    public function myCustomEvenListener(e:MouseEvent,myCustomData:Object)
    {
    //Do whatever you wnat with myCustomData Object here...
    }
    //this is the function where you add event listeners to components..
    public function init():void
    {
    var myCustomObject:Object=new Object();
    myCustomObject.url="http://xyz.com/image.jsp";
    myCustomObject.anydata="You can Add anything here";
    
    mycomponent.addEventListener(MouseEvent.CLICK,function (e:MouseEvent) : void {
                      myCustomEventListener(e,myCustomObject);
                });
    
    }
    

    This is just another way of using anonymous functions though....

    0 讨论(0)
  • 2020-12-06 07:12

    (I think you'll want to read this answer.)

    Regarding your doubt, you felt it yourself: your leprechaun's smelly (pun). Imagine it's a Sprite instead of a MovieClip. It isn't dynamic, so you can't add properties unless you do like Richard said.

    Here's the better solution you wished, based on your example:

    tempThumb.addEventListener(MouseEvent.CLICK, loadImage("large.jpg"));
    
    public function loadImage(_url:String):Function {
      return function(_event:MouseEvent):void {
        // Now you have both variables _url and _event here!
      }
    }
    

    But you want to be able to remove listeners, so:

    var functionLoadImage:Function = loadImage("large.jpg");
    tempThumb.addEventListener(MouseEvent.CLICK, functionLoadImage);
    
    public function loadImage(_url:String):Function {
      return function(_event:MouseEvent):void {
        // Now you have both variables _url and _event here!
      }
    }
    
    //trace(tempThumb.hasEventListener(MouseEvent.CLICK));
    tempThumb.removeEventListener(MouseEvent.CLICK, functionLoadImage);
    //trace(tempThumb.hasEventListener(MouseEvent.CLICK));
    
    0 讨论(0)
提交回复
热议问题