簡體   English   中英

聆聽主類AS3上的自定義事件

[英]Listen Custom Events on Main Class AS3

這是我在動作腳本中的小問題。 為了簡單起見,我將兩個小類放在一起來演示我的問題。

所以從RedState.as調度自定義事件,女巫將字符串傳遞給偵聽器。 我想聽這個事件並在根類中獲取傳遞的字符串。

如果我在另一個類中聽同一個事件,一切似乎都很好,但是主類沒有反應:(:D

package 
{
    import assets.ButtonController;
    import flash.display.Sprite;
    import flash.events.Event;
    import flash.events.MouseEvent;


    public class Main extends Sprite 
    {

        public var nameCollection:Array
        public var sManager:SceneManager
        public var cText:TempClass
        public var bManager:ButtonController;

        public var red:RedState
        public function Main():void 
        {   
            addEventListener(Event.ADDED_TO_STAGE, init);
        }
        public function init (e:Event):void {
            red = new RedState();
            addChild(red);
            addEventListener(TextDispatcher.SEND_TEXT, red_sendText);

        }

        public function red_sendText(e:TextDispatcher):void 
        {   trace ("Something")
            trace (e.url)
        }





    }

}


package  
{
    import flash.display.Sprite;

    public class RedState extends Sprite 
    {
        [Embed(source = "assets/states/red.png")]
        public var Red:Class;

        public var red:Sprite;

        public function RedState() 
        {
            red = new Sprite();
            red.addChild(new Red());
            addChild(red);
            dispatchEvent(new TextDispatcher(TextDispatcher.SEND_TEXT, "I wanna Sing!!"))

        }

    }

}

如果我理解正確,你正在試圖派遣TextDispatcher.SEND_TEXTRedState類。 假設一切均已正確設置,則有兩個原因說明為什么未調度事件。 首先是您沒有將偵聽器添加到RedState實例。 那是:

public function init (e:Event):void {
    red = new RedState();
    red.addEventListener(TextDispatcher.SEND_TEXT, red_sendText);
    addChild(red);
}

加上它,將使dispatchEvent從RedState開始工作,因為現在RedState實例將在監聽它。 但是RedState構造函數中還有另一個問題:

public function RedState() {
    red = new Sprite();
    red.addChild(new Red());
    addChild(red);
    //trying to dispatch here will not work
    dispatchEvent(new TextDispatcher(TextDispatcher.SEND_TEXT, "I wanna Sing!!"))
 }

您正在嘗試在添加偵聽器之前調度事件。 當前沒有任何對象帶有此事件的偵聽器,因此它永遠無法運行red_sendText()

因此,您應該執行以下操作:

public function init(e:Event):void {
    red = new RedState();
    red.addEventListener(TextDispatcher.SEND_TEXT, red_sendText);
    red.runText();
    addChild(red);
}

然后在您的RedState中:

public function RedState() {
    red = new Sprite();
    red.addChild(new Red());
    addChild(red);
}

public function runText():void {
    dispatchEvent(new TextDispatcher(TextDispatcher.SEND_TEXT));
}

現在,您的RedState實例將在調用runText()之前監聽事件。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM