How to create custom MouseEvent.CLICK event in AS3 (pass parameters to function)?

前端 未结 6 1990
执念已碎
执念已碎 2021-01-05 05:50

This question doesn\'t relate only to MouseEvent.CLICK event type but to all event types that already exist in AS3. I read a lot about custom events but until now I couldn\'

6条回答
  •  灰色年华
    2021-01-05 06:43

    I see your main goal isn't actually to create a custom MouseEvent.CLICK, but to pass a parameter to the function. You don't need to complicatedly create or extend anything. There's a simple and closure-trouble-free way to do it.

    Just make your function like this:

    function doSomething(index:Number):Function {
      return function(e:MouseEvent):void {
        // Use "e" and "index" here. They'll be unique for each addEventListener()
        trace(index);
      }
    }
    

    This technique can relate to any AS3 event type you can use addEventListener on.

    And now you can add it like this:

    var functionsDoSomething:Object;
    
    for (var i:Number = 0; i < 10; i++) {
      var someVar:Number = i;
      functionsDoSomething[i] = doSomething(someVar);
      myClips[i].addEventListener(MouseEvent.CLICK, functionsDoSomething[i]);
    }
    

    The doSomething(someVar) can be used directly on addEventListener(), but it's better to keep it in a variable because you'll be able to remove it later the same fashion you added it:

    for (i = 0; i < 10; i++) {
      myClips[i].removeEventListener(MouseEvent.CLICK, functionsDoSomething[i]);
    }
    

    The commonly used e.currentTarget.someCustomProperty works for dynamic objects (i.e. MovieClip), but will let you down at anything else (i.e. Sprite), forcing you to build a whole custom extended object/event for every type.

    This solution deals with every "listenable" object and event. And this answer has more details and examples on it.

提交回复
热议问题