如何将定时器事件分派到另一个类



我试图从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中。

    public function Main()
    {
        // constructor code
        _timer = new MyTimer  ;
        stage.addEventListener("tickTack", ontickTack);
    }
    function ontickTack(e:Event)
    {
        sus--;
        trace(sus);
    }    

在您的Main.as中,您已将侦听器添加到舞台,而不是计时器。这条线:

stage.addEventListener("tickTack", ontickTack);

应该像这样:

_timer.addEventListener("tickTack", ontickTack);

但是ActionScript已经有一个Timer类,看起来它有你需要的所有功能。没有必要重新发明轮子。看一下Timer类的文档。

你可以直接说:

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.
}

最新更新