【发布时间】:2011-01-31 21:25:25
【问题描述】:
我尝试从舞台上的某个组件分派自定义事件,我注册了另一个组件来监听它,但另一个组件没有收到该事件。
这是我的代码;我错过了什么?
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;
}
}
我不想写在 Main
compSource.addEventListener(ScoreChanged.SCORE_GAIN, compMenu.updateScore);
因为我不想让 compSource 知道 compMenu; compMenu 有责任知道它需要监听哪些事件。
【问题讨论】:
标签: actionscript-3 flash events