Sunday, 28 September 2014

Events, Listeners and Handlers

So.. Its been quite a pause with what we have learnt so far. Lets proceed!

This topic is about the how Flash interprets every action that the user makes inside a frame (Sprite/MovieClip). Actions that happen within the frame are called events (as the name says). Since we are talking about communicating with the user, we gotta listen to the user about what the user does and we gotta handle the every user actions appropriately. I hope I have covered the context!

Now, lets get into theory.

Event: Events are actions that happens when the user performs something with the keyboard or mouse within the sprite

Listeners: Listeners are subscribers of events. These listeners will be linked to the objects within the sprite and whenever the event occurs, the listener will get notified of the events

Handlers: Handlers are functions that handles the action that has to be performed in occurance of a particular event

Below is an example of event, listener and handler

addEventListener(MouseEvent.MOUSE_DOWN, onSpritePress);

where 'MouseEvent' is the event, 'MOUSE_DOWN' is the listener and 'onSpritePress' is the handler

Additionally, if you no longer need to listen to an object (if you do not want any action to be performed on an object even is any event is occurred in the object), you can remove the event listeners as well, like below

removeEventListener(MouseEvent.MOUSE_DOWN, onSpritePress);

Alright, thats enough theory. Time to make our hands dirty!

package {
 import flash.display.Sprite;
 import flash.display.StageAlign;
 import flash.display.StageScaleMode;

 public class EventDemo extends Sprite {
  private var eventSprite:Sprite;
  public function EventDemo() {
  private function init():void {
   stage.scaleMode = StageScaleMode.NO_SCALE;
   eventSprite = new Sprite();
   addChild(eventSprite);;, 0, 100);;
   eventSprite.x = stage.stageWidth / 2;
   eventSprite.y = stage.stageHeight / 2;
   eventSprite.addEventListener(MouseEvent.MOUSE_DOWN, onMouseDown);
   eventSprite.addEventListener(MouseEvent.MOUSE_UP, onMouseUp);
  private function onMouseDown(event:MouseEvent):void {
   trace("mouse down");
  private function onMouseUp(event:MouseEvent):void {
   trace("mouse up");

As you would see, when you run it; the console gets updated with the lines 'mouse down' and 'mouse up' whenever the mouse is clicked within the red ball!

Note: If you do not get the above mentioned message in the console, don worry, the flash player that you use might have probably been downgraded. Trust me, its no big deal. We have that covered in the upcoming lessons :-)