ActionScript: How to listen for an event from a different XML

51 views Asked by At

I have a popup screen in which the player enters their name and clicks OK. When OK is clicked I want the player's name to be passed to the main XML. How can I do this?

Here is the function in the main XML that handles the popup:

    private function NewHighScore():void{
        highScorePopup = PopUpManager.createPopUp(this, Popup, true) as Popup;
        highScorePopup.SetScore(playerscore);
        PopUpManager.centerPopUp(highScorePopup);
        playerName = highScorePopup.getName();
        trace(playerName);
    }

And here is the popup XML script:

        import mx.events.CloseEvent;
    import mx.managers.PopUpManager;

    import spark.events.TextOperationEvent;
    public var playerName:String;

    public function SetScore (playerScore:int):void{
        scoreDisplay.text = "You achieved a new high score of " + playerScore.toString();
    }

    protected function button1_clickHandler(event:MouseEvent):void{ remove(); }

    private function remove():void{ PopUpManager.removePopUp(this);}

    protected function titlewindow1_closeHandler(event:CloseEvent):void
    { remove();}

    protected function nameBox_changeHandler(event:TextOperationEvent):void
    {playerName = nameBox.text;}

    public function getName():String{
    return playerName;
    }
1

There are 1 answers

1
Vesper On BEST ANSWER

Waiting for player to enter their name is an asynchronous process, therefore you have to wait for an event dispatched by the popup. Since the popup closes itself (gets removed from stage) once OK button is clicked, you can listen on that popup for Event.REMOVED_FROM_STAGE event, and only then gather the data from the popup. Don't for get to remove the event listener from the popup so that you'll not leak the instance.

private function NewHighScore():void{
    highScorePopup = PopUpManager.createPopUp(this, Popup, true) as Popup;
    highScorePopup.SetScore(playerscore);
    PopUpManager.centerPopUp(highScorePopup);
    highScorePopup.addEventListener(Event.REMOVED_FROM_STAGE,getPlayerName);
}
function getPlayerName(event:Event):void {
    event.target.removeEventListener(Event.REMOVED_FROM_STAGE,getPlayerName);
    var popup:Popup=event.target as Popup;
    if (!popup) return;
    var playerName:String=popup.getName(); // now the name will be populated
    // do stuff with the name
}