AS3:EventListener在[IF]中被删除

时间:2014-06-19 20:19:04

标签: actionscript-3 flash events actionscript listener

我已经搜索了如何通过EventListeners传递参数,并且我在不调用匿名函数的情况下使用该方法以便稍后删除EventListener。

问题是,如果退出IF函数,EventListener将被删除,但如果它在IF函数中则不会被删除。 我怎么能这样做?

代码:

function dragShip(m:MouseEvent):void
{
    var func:Function = dispositionShip(m.target);

    if (isDragging == false)
    {
        stage.addEventListener(KeyboardEvent.KEY_DOWN, func);
        m.target.startDrag(true);
        isDragging = true;
    }
      else
    {
        stage.removeEventListener(KeyboardEvent.KEY_DOWN, func);
        isDragging = false;
        placeShip(m.target , mouseX , mouseY , m.target.rotation);
    }
    // if the EventListener is put here, it gets removed, but not if put just in the else
}

注意dispositionShip()会返回函数

编辑:以下是代码的以下部分:

function dispositionShip(shipTarg):Function
{
    return function(k:KeyboardEvent):void
    {
        rotateShip(k,shipTarg);
    };
}

function rotateShip(k:KeyboardEvent,ship:Object):void
{
    if (k.keyCode == 39)
    {
        ship.rotation += 90;
    } 
    else if (k.keyCode == 37)
    {
        ship.rotation -= 90;
    } 
}

此外,如果我用简单的rotateShip(k,shipTarg);替换trace,它也无效。

1 个答案:

答案 0 :(得分:1)

每次致电

function dispositionShip(shipTarg):Function
{
    return function(k:KeyboardEvent):void
    {
        rotateShip(k,shipTarg);
    };
}

您正在创建一个名为Object的新匿名Function,呼叫rotateShip(),因此当您致电stage.removeEventListener(KeyboardEvent.KEY_DOWN, func);时,funcObject不同func 1}}传递给addEventListener() var,因此它与原始侦听器不匹配,并且不会被删除。

更好的方法是将当前鼠标目标存储在成员var currentShip:Object; function dragShip(m:MouseEvent):void { if (isDragging == false) { stage.addEventListener(KeyboardEvent.KEY_DOWN, keyPress); m.target.startDrag(true); isDragging = true; currentShip = m.target; } else { stage.removeEventListener(KeyboardEvent.KEY_DOWN, keyPress); isDragging = false; placeShip(m.target , mouseX , mouseY , m.target.rotation); currentShip = null; } } function keyPress(k:KeyboardEvent):void { rotateShip(k,currentShip); } 中。 IE:

{{1}}