I read a lot of topics about dispatching event but I can't make my code work. This topic and this topic are closed to what I would like to do, but it's not working in my case.
Here is the situation :
- My scene is a battle field and has two ships
- Each ship knows when it is touched by a fire, so it has to inform the scene that contains the graphic interface
- So the ship dispatch a custom event with itself as parameter, so the scene knows when a ship is touched and which ship
I have 3 classes :
- The custom event class is an event that has a property "Ship"
- The EventDispatcher class
- The symbole class that corresponds to my scene and listen to the event
1) CustomEvent class
public class FightEvent extends Event
{
public static const SHIP_TOUCHED:String = "SHIP_TOUCHED"; //type
public var object:Ship = null; //object to pass
public function FightEvent(type:String, pObject:Ship, bubbles:Boolean=true, cancelable:Boolean=false)
{
super(type, bubbles, cancelable);
object = pObject;
}
public override function clone():Event
{
return new FightEvent(type, object, bubbles, cancelable);
}
}
2) EventDispatcher
public class Ship extends EventDispatcher
{
private function updateDamages():void
{
//compute damages
dispatchEvent( new FightEvent( FightEvent.SHIP_TOUCHED, this ) );
}
}
3) Scene
public class Fight extends customMovieClip
{
private var playerShip:Ship; //I have two ships, player and enemy
private var enemyShip:Ship;
public function init():void
{
stage.addEventListener(FightEvent.SHIP_TOUCHED, onShipTouched);
//I made a test : the event listener is correctly added
}
private function onShipTouched(e:FightEvent):void
{
//update the graphic interface to show damages
}
}
My event listener is added, the code passes on the dispatch line, but onShipTouched is not called.
Please help, what did I miss ?
What is the element I didn't understand ?
Is it a good way to use events like this ? or should I set a reference to the scene inside the Ship class ?
Shipdoes that.addEventListeneranddispatchEvent, or probably even scenes, thus thestageis different at the time of attaching the listener and the time when the event is fired, so the event reaches wrong stage and is dropped with no reaction.