2013-04-15 40 views
0

我想從Mytimer類每秒發送一次事件並從Main類捕獲事件。我已經聲明變量「sus」爲整數= 10。到目前爲止我沒有任何東西,沒有輸出,什麼都沒有。請幫助一些!AS3如何將計時器事件分派給其他課程?

這是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); 
    }  

回答

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

謝謝,謝謝。這是我正在尋找的。感謝你及時的答覆。我這樣做是因爲我想保留我的計時器在單獨的課程中,所以我可以隨時訪問它的計時。我發現這種方式非常方便。謝謝Adam – irnik

+0

不用擔心@irnik,如果你找到你想要的東西,記得標記答案是正確的。 –

相關問題