如何在向其添加新的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);
}
}
每隔X秒调用一次函数countDown,并传递新的datetoProcess值。但是,每次调用此函数时,都会添加一个新的TimerEvent.TIMER EventListener,因为代码告诉它,无论如何在添加新的事件之前删除当前的事件侦听器?
我试过了:
if (myTimer.hasEventListener(TimerEvent.TIMER))
{
myTimer.stop();
myTimer.removeEventListener(TimerEvent.TIMER, countdown);
trace("remove");
}
但似乎没有工作,它仍然添加事件Listener,我使用trace(myTimer.currentcounter)和输出如: 1 2 2 3 3 3 4 4 4 4 有人可以帮忙解决这个问题吗?
答案 0 :(得分:0)
Still not sure what you're after for, but here's one shot using the same Timer:
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);
}
Or:
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);
}
So it works as you thought it would, you probably just had something in wrong place?