Flash - Dispatching and listening to Signals PDF Print E-mail
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


	import org.osflash.signals.Signal;

	

We just need to add two Signals to the SpaceShip class:


	public var onShot : Signal;

	public var onExploded : Signal;

	

Then, in the class constructor, initialize them


	onShot = new Signal();

	onExploded = new Signal();

	

Now,  we will dispatch those signals in the related methods:


	public function shoot():void{

	   //shoot deadly lasers etc

	   onShot.dispatch();

	}

	 

	public function explode():void{

	   //remove ship etc.

	   onExploded.dispatch();

	}

	
 
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:


	var ship : SpaceShip = new SpaceShip();

	ship.onExploded.add(shipExploded);

	ship.onShot.add(shipShot);

	

Then, create the related methods:


	
		private function shipExploded():void{
	
		   trace("SHIP EXPLODED");
	
		}
	
		 
	
		private function shipShot():void{
	
		   trace("SHIP SHOT");
	
		}
	
		 
	

		

As you can see, we simply trace that our ship sent a signal. 

Let's test it, and call both methods:

	

		ship.shoot();
	

		ship.explode();
	

		

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:

	

		ship.onShot.addOnce(shipShot);
	

		

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:

	

		ship.onShot.remove(shipShot);
	

		

Or removeAll to remove all listeners from a signal:

	

		ship.onShot.removeAll();
	

		

 

Add comment


Security code
Refresh