2010-03-25 36 views
2

我試圖從舞臺上的某個組件派發自定義事件,並且我註冊了另一個組件以偵聽它,但另一個組件未獲取該事件。操作腳本中的事件流程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有責任瞭解它需要聆聽哪些事件。

回答

0

遊戲和菜單似乎是在事件鏈不同的鏈。事件向上冒泡,因爲遊戲和菜單是兄弟姐妹,他們將無法訪問彼此的事件。

一個解決辦法是讓你從主屏幕發送到菜單中的遊戲的參考。然後從該菜單中添加一個事件監聽器。

0

桑德羅是正確的,因爲事件冒泡,不側身,你Menu將再也看不到該事件。

一個可能的解決方案:爲Main已經「知道」既compSourcecompMenu您可以安全地通過主類傳遞事件:

class Main{ 
    public function Main() 
    { 
     compSource = new Game(); 
     compSource.addEventListener(ScoreChanged.SCORE_GAIN, scoreGainHandler); 
     compMenu = new Menu(); 
     //... rest of constructor 
    } 

    public function scoreGainHandler(event:ScoreChanged):void 
    { 
     compMenu.updateScore(event); 
    } 
    //... rest of class 

這樣獨立的GameMenu住宿。

事實上,如果你建立了這種方式,Menu並不需要聽的得分​​變化情況可言,你可以改變更新功能需要一個得分變量:

class Menu{ 

    public function updateScore(score:int):void 
    { 
     tScore.text = String(score); 
    } 
    //... etc