【问题标题】:Actionscript 3 EventListenerActionscript 3 事件监听器
【发布时间】:2016-10-02 00:10:48
【问题描述】:

我对 actionscript 3 相当陌生,我想知道如何让 EventListener 只工作一次。现在它在每次点击后都可以工作,但我需要让它只在第一次点击时工作。 单击后,它会在单击的舞台上显示一个球。我需要到达只出现一个球的地步,然后单击应该什么都不做。

我的代码:

stage.addEventListener(MouseEvent.CLICK, onClick,false,0,true);
function onClick(evt:MouseEvent):void {
    var ball:MovieClip = new Ball();
    ball.x = stage.mouseX;
    ball.y = stage.mouseY;
    addChildAt(ball,0);
}

【问题讨论】:

    标签: actionscript-3 flash


    【解决方案1】:

    一种可能的解决方案是删除 EventListener。

    stage.addEventListener(MouseEvent.CLICK, onClick,false,0,true);
    function onClick(evt:MouseEvent):void {
        stage.removeEventListener(MouseEvent.CLICK, onClick);
        var ball:MovieClip = new Ball();
        ball.x = stage.mouseX;
        ball.y = stage.mouseY;
        addChildAt(ball,0);
    }
    

    另一个解决方案是一个简单的布尔变量,以防您需要事件监听器来处理其他事情。

    var clickedOnce:Boolean = false;
    stage.addEventListener(MouseEvent.CLICK, onClick,false,0,true);
    function onClick(evt:MouseEvent):void {
        if(!clickedOnce){
           clickedOnce = true;
           var ball:MovieClip = new Ball();
           ball.x = stage.mouseX;
           ball.y = stage.mouseY;
           addChildAt(ball,0);
        }
    }
    

    【讨论】:

      【解决方案2】:

      您需要拨打removeEventListener()如下:

      stage.addEventListener(MouseEvent.CLICK, onClick,false,0,true);
      function onClick(evt:MouseEvent):void {
          stage.removeEventListener(MouseEvent.CLICK, onClick);
          var ball:MovieClip = new Ball();
          ball.x = stage.mouseX;
          ball.y = stage.mouseY;
          addChildAt(ball,0);
      }
      

      【讨论】: