我試圖從舞臺上的某個組件派發自定義事件,並且我註冊了另一個組件以偵聽它,但另一個組件未獲取該事件。操作腳本中的事件流程3
這是我的代碼;我錯過了什麼?
public class Main extends MovieClip //main document class
{
var compSource:Game;
var compMenu:Menu;
public function Main()
{
compSource = new Game;
compMenu = new Menu();
var mc:MovieClip = new MovieClip();
addChild(mc);
mc.addChild(compSource); // the source of the event - event dispatch when clicked btn
mc.addChild(compMenu); //in init of that Movie clip it add listener to the compSource events
}
}
public class Game extends MovieClip
{
public function Game()
{
btn.addEventListener(MouseEvent.CLICK, onFinishGame);
}
private function onFinishGame(e:MouseEvent):void
{
var score:Number = Math.random() * 100 + 1;
dispatchEvent(new ScoreChanged(score));
}
}
public class Menu extends MovieClip
{
//TextField score
public function Menu()
{
addEventListener(Event.ADDED_TO_STAGE, init);
}
private function init(e:Event):void
{
removeEventListener(Event.ADDED_TO_STAGE, init);
//on init add listener to event ScoreChanged
addEventListener(ScoreChanged.SCORE_GAIN, updateScore);
}
public function updateScore(e:ScoreChanged):void
{
//it never gets here!
tScore.text = String(e._score);
}
}
public class ScoreChanged extends Event
{
public static const SCORE_GAIN:String = "SCORE_GAIN";
public var _score:Number;
public function ScoreChanged(score:Number)
{
trace("new score");
super(SCORE_GAIN, true);
_score = score;
}
}
我不想在主
compSource.addEventListener(ScoreChanged.SCORE_GAIN, compMenu.updateScore);
寫,因爲我不想compSource知道關於compMenu; compMenu有責任瞭解它需要聆聽哪些事件。