I am making a game using AS3. I have three classes (Spaceship, UFO, and Scoreboard) which are all children of the class GameEngine.

I want to put eventListeners in Scoreboard and then send dispatchEvents from Spaceship and UFO to update the scoreboard instance.

Since Spaceship and UFO are neither parents or children of Scoreboard, adding a bubbling=true parameter to the dispatchEvent does nothing.

How do I get Scoreboard to listen for *dispatchEvent*s without doing this:

GameEngine.scoreboard.dispatchEvent(new Event("shipWasHit", true));

This seems silly to do it this way. Why would I use a dispatchEvent at all -- why not call the function directly? And what if I want other classes to listen for the same dispatchEvent?

Please advise.

4

There are 4 answers

0
frankhermes On

Your Spaceships and UFO's would do this:

dispatchEvent(new Event("shipWasHit"));

and your Scoreboard would need to know which spaceships and UFO's to listen to for those events:

someShip.addEventListener("shipWasHit", onShipHit);

and

thatUFO.addEventListener("shipWasHit", onUFOHit);

A good place to add those listeners is in the class that creates those Spaceships and UFO's, or in the Scoreboard itself if at some point you tell it what ships and UFO's to listen to.

1
Ribs On
0
AudioBubble On

Since any event that uses either the capture phase or bubble phase that doesn't have its propagation interrupted runs through the stage, you can just add a listener for the stage inside of the specified class.

Example code:

public function Receiver()
{
    addEventListener(Event.ADDED_TO_STAGE, added, false, 0, true);
}

private function added(evt:Event):void
{
    stage.addEventListener(Event.shipWasHit, shipHit, false, 0, true);
}

private function shipHit(evt:Event):void
{
    //code
    evt.stopPropagation();
}

Now, there are a few caveats here. First off, this class needs to be instantiated and added to the stage in order to reference the stage. Otherwise, you'll need to pass in the stage as a parameter, and that can return null in cases. Finally, you'll have to instantiate this before the event is dispatched, though this doesn't seem to be a problem with the code I'm seeing right now.

0
www0z0k On