如何在添加新事件监听器之前删除当前事件监听器
How to remove current Event Listener before adding new one
如何在添加新的 EventListener 之前删除当前的 EventListener?我在下面的代码中做了一个简单的倒计时:
var myTimer:Timer = new Timer(1000);
function countDown(dateToProcess):void
{
myTimer.addEventListener(TimerEvent.TIMER, countdownTimer);
myTimer.start();
function countdownTimer(e:Event):void
{
//display dateToProcess.getTime() - today.getTime();
trace(myTimer.currentCounter);
}
}
函数 countDown 每 X 秒调用一次,新的 datetoProcess 值将被传递。但是,每次调用此函数时,都会添加一个新的 TimerEvent.TIMER EventListener,因为代码告诉它这样做,是否有办法在添加新事件监听器之前删除当前事件监听器?
我试过:
if (myTimer.hasEventListener(TimerEvent.TIMER))
{
myTimer.stop();
myTimer.removeEventListener(TimerEvent.TIMER, countdown);
trace("remove");
}
但似乎没有用,它仍在添加事件监听器,我使用了 trace(myTimer.currentcounter) 并输出如下:
1个
2个
2个
3个
3个
3个
4个
4个
4个
4个
有人可以帮忙解决这个问题吗?
仍然不确定您要做什么,但这是使用相同计时器拍摄的一张:
var myTimer:Timer = new Timer(1000,0);
function countDown(dateToProcess):void{
myTimer.addEventListener(TimerEvent.TIMER, countdownTimer);
myTimer.start();
}
function countdownTimer(e:TimerEvent):void{
myTimer.stop();
myTimer.removeEventListener(TimerEvent.TIMER, countdownTimer);
trace(myTimer.currentCount);
}
或者:
function countDown(dateToProcess):void{
if(myTimer.hasEventListener(TimerEvent.TIMER)){
myTimer.stop();
myTimer.removeEventListener(TimerEvent.TIMER, countdownTimer);
}
myTimer.addEventListener(TimerEvent.TIMER, countdownTimer);
myTimer.start();
}
function countdownTimer(e:TimerEvent):void{
trace(myTimer.currentCount);
}
所以它像你想象的那样工作,你可能只是错了地方?
如何在添加新的 EventListener 之前删除当前的 EventListener?我在下面的代码中做了一个简单的倒计时:
var myTimer:Timer = new Timer(1000);
function countDown(dateToProcess):void
{
myTimer.addEventListener(TimerEvent.TIMER, countdownTimer);
myTimer.start();
function countdownTimer(e:Event):void
{
//display dateToProcess.getTime() - today.getTime();
trace(myTimer.currentCounter);
}
}
函数 countDown 每 X 秒调用一次,新的 datetoProcess 值将被传递。但是,每次调用此函数时,都会添加一个新的 TimerEvent.TIMER EventListener,因为代码告诉它这样做,是否有办法在添加新事件监听器之前删除当前事件监听器?
我试过:
if (myTimer.hasEventListener(TimerEvent.TIMER))
{
myTimer.stop();
myTimer.removeEventListener(TimerEvent.TIMER, countdown);
trace("remove");
}
但似乎没有用,它仍在添加事件监听器,我使用了 trace(myTimer.currentcounter) 并输出如下: 1个 2个 2个 3个 3个 3个 4个 4个 4个 4个 有人可以帮忙解决这个问题吗?
仍然不确定您要做什么,但这是使用相同计时器拍摄的一张:
var myTimer:Timer = new Timer(1000,0);
function countDown(dateToProcess):void{
myTimer.addEventListener(TimerEvent.TIMER, countdownTimer);
myTimer.start();
}
function countdownTimer(e:TimerEvent):void{
myTimer.stop();
myTimer.removeEventListener(TimerEvent.TIMER, countdownTimer);
trace(myTimer.currentCount);
}
或者:
function countDown(dateToProcess):void{
if(myTimer.hasEventListener(TimerEvent.TIMER)){
myTimer.stop();
myTimer.removeEventListener(TimerEvent.TIMER, countdownTimer);
}
myTimer.addEventListener(TimerEvent.TIMER, countdownTimer);
myTimer.start();
}
function countdownTimer(e:TimerEvent):void{
trace(myTimer.currentCount);
}
所以它像你想象的那样工作,你可能只是错了地方?