【问题标题】:AS3 How to dispatch timer event to another class?AS3 如何将定时器事件分派给另一个类?
【发布时间】:2013-04-15 07:17:05
【问题描述】:

我正在尝试每秒从 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);
    }    

【问题讨论】:

    标签: actionscript-3 timer dispatch


    【解决方案1】:

    在您的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.
    }
    

    【讨论】:

    • 谢谢,谢谢。这就是我一直在寻找的。感谢您及时回复。我这样做是因为我想把我的计时器放在单独的班级里,所以我可以随时访问它的时间。我发现这种方式非常方便。谢谢亚当
    • 别担心@irnik,如果你找到了你想要的,记得把答案标记为正确。
    猜你喜欢
    • 1970-01-01
    • 2013-04-22
    • 2013-10-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多