AS3如何将计时器事件调度到另一个类?

时间:2013-04-15 07:17:06

标签: actionscript-3 timer dispatch

我试图从Mytimer类每秒调度一次事件并从Main类中捕获事件。我已经将变量“sus”声明为整数= 10.我到目前为止没有任何东西,没有输出,没有。请帮忙!

这是Mytimer.as

    private function onUpdateTime(event:Event):void
    {

        nCount--;
        dispatchEvent(new Event("tickTack", true));
        //Stop timer when it reaches 0
        if (nCount == 0)
        {
            _timer.reset();
            _timer.stop();
            _timer.removeEventListener(TimerEvent.TIMER, onUpdateTime);
            //Do something
        }
    }    

在Main.as我有:

    public function Main()
    {
        // constructor code
        _timer = new MyTimer  ;
        stage.addEventListener("tickTack", ontickTack);
    }

    function ontickTack(e:Event)
    {
        sus--;
        trace(sus);
    }    

1 个答案:

答案 0 :(得分:2)

Main.as中,您已将听众添加到舞台,而不是计时器。这一行:

stage.addEventListener("tickTack", ontickTack);

应该是这样的:

_timer.addEventListener("tickTack", ontickTack);

但ActionScript已经有一个Timer类,看起来它具有您需要的所有功能。无需重新发明轮子。看看documentation for the Timer class

在你的主要内容你可以说:

var count:int = 10; // the number of times the timer will repeat.
_timer = new Timer(1000, count); // Creates timer of one second, with repeat.
_timer.addEventListener(TimerEvent.TIMER, handleTimerTimer);
_timer.addEventListener(TimerEvent.TIMER_COMPLETE, handleTimerTimerComplete);

然后只需添加处理程序方法。您不需要同时使用它们。通常TIMER事件就足够了。像这样:

private function handleTimerTimerComplete(e:TimerEvent):void 
{
    // Fires each time the timer reaches the interval.
}

private function handleTimerTimer(e:TimerEvent):void 
{
    // Fired when all repeat have finished.
}
相关问题