|Articles & Tutorials|
|Flash - Dispatching and listening to Signals|
|Sunday, 12 February 2012 23:05|
Let's see how to dispatch Signals first.
Let's say we are developing a shmup, and we want to know when our spaceship shoot and when it explodes.
Import the Signal class
We just need to add two Signals to the SpaceShip class:
Then, in the class constructor, initialize them
Now, we will dispatch those signals in the related methods:
Let's see now how to listen to those signals now. To do that, we need to create a new Ship and add listeners to its signals, in this way:
Then, create the related methods:
As you can see, we simply trace that our ship sent a signal.
Let's test it, and call both methods:
And, as expected, we'll see both traces in our Console.
Another useful method is the addOnce method, that lets you listen to a signal only once, and then automatically remove the listener.
In this case, just do this:
shipShot will be called only once.
If we later need to remove listeners from our signal we can use remove to remove a single listener:
Or removeAll to remove all listeners from a signal: