2014-01-25 178 views
0

這裏是我的代碼,我不知道爲什麼它不刪除事件監聽器。AS3 - 刪除事件監聽器失敗

我想要做的是有一些按鈕來打開和關閉根據節拍的聲音。在第一次點擊時它完美地工作,但是當我想在第二次點擊時移除聲音時,它不能移除事件監聽器。

plat.BEAT1.addEventListener(TouchEvent.TOUCH_BEGIN, BEATDown(plat.BEAT1, hihatz, 2)); 
plat.BEAT2.addEventListener(TouchEvent.TOUCH_BEGIN, BEATDown(plat.BEAT2,cymbalz, 4));  

function BEATDown (padNum, sounz, tiempo) { 

    return function (e:TouchEvent) { 

     var currentSound:Sound = null; 
     var currentSoundChannel:SoundChannel; 
     var active:int; 

     if (padNum.currentFrame == 1) { 
      padNum.gotoAndStop(3); 
      padNum.addEventListener(Event.ENTER_FRAME, PlayBeats); 
      active = 1; 

     } else { 
      padNum.gotoAndStop(1); 
      padNum.removeEventListener(Event.ENTER_FRAME, PlayBeats); 
      active = 0; 
     } 

     function playSound(sound:Sound):void 
      { 

       if (active == 0) 
       { 
        // Stop playing ANY sound 
        currentSound = null; 
        currentSoundChannel = null; 
       } 
       else 
       { 
        // Play a different sound 
        currentSound = sound; 
        currentSoundChannel = sound.play(); 
       } 
      } 


     function PlayBeats(event:Event):void 
      { 

       if (tiempo == 1) { 
        if (fl_SecondsElapsed <= 4) { 
         playSound(sounz); 
        } 
       } 
       if (tiempo == 2) { 
        if (fl_SecondsElapsed == 1 || fl_SecondsElapsed == 3) { 
         playSound(sounz); 
        } 
       } 
       if (tiempo == 4) { 
        if (fl_SecondsElapsed == 1) { 
        playSound(sounz); 
       } 

       } 

      } 

    } 

} 

編輯: 我想刪除的listener padNum.addEventListener(Event.ENTER_FRAME,PlayBeats); plat.BEAT1是按鈕實例。我使用多個實例來觸發不同的聲音,根據Tiempo計數,每個聲音開啓和關閉。

+0

哪個事件監聽器有問題? TOUCH_BEGIN或ENTER_FRAME監聽器的匿名函數? – frankhermes

回答

0

我會說這是因爲你不在相同的對象上添加/刪除你的監聽器; 是plat.BEAT1和plat.BEAT2是一樣的嗎?我猜不會。

我建議你嘗試在這個或父元素上的舞臺上添加EnterFrame監聽器,以便正確刪除事件。然後如果你想讓你的對象獨立工作,請嘗試定位正確的對象。

if (padNum.currentFrame == 1) { 
    padNum.gotoAndStop(3); 
    stage.addEventListener(Event.ENTER_FRAME, PlayBeats); 
    active = 1; 
} else { 
    padNum.gotoAndStop(1); 
    stage.removeEventListener(Event.ENTER_FRAME, PlayBeats); 
    active = 0; 
} 
+0

是的,這就是我想要做的。儘管不起作用,聽衆仍然存在。 – RuvaloLU