AS 3 Custom Event
December 23rd, 2007
For years I avoided the event system in AS 2. It was horrible and it couldn’t keep it’s scope. Now that I am working in AS 3 I am trying my hardest to like the new event system and event class. Unfortunately it is missing one thing I always needed it to do, pass off data or an object along with the event. Here is how I get around it.
To combat this problem I create a new Event class that extends the base Event class in AS 3. Since I organize my projects as applications I tend to create one event named after the application and use that as the default event type throughout the code. Here is an example class from a slide show app I was building.
SlideShowEvent
Created by Jesse Freeman on 2007-04-28.
*/
package com.jessefreeman.slideshow.v1.events{
import flash.events.Event;
public class SlideShowEvent extends Event{
public static const LOADING_IMAGE:String = “loading_image”;
public static const IMAGE_LOADED:String = “image_loaded”;
public static const NEXT_IMAGE:String = “next_photo”;
public static const PREVIOUS_IMAGE :String = “previous_photo”;
public static const PAUSE:String = “pause”;
public static const PLAY:String = “play”;
public static const LOAD_GALLERY:String = “load_gallery”;
public static const GALLERY_LOADED:String = “gallery_loaded”;
private var _data:*;
public function get data():*{
return _data;
}
public function SlideShowEvent(type:String, data:* = null, bubbles:Boolean = false, cancelable:Boolean = false){
super(type, bubbles, cancelable);
_data = data;
}
}
}
Take a look at the constructor and notice how I add a “data” parameter and type it to *1.
See how I have a private var _data and a getter for data. This is how I can get the data out of the event. There really isn’t anything else to it but now you should have a way to send data along with an event. This is key to ruling the world! On to the final set of examples.
Here is an example of how I add some event listeners for this class
_controls = controls;
_controls.addEventListener(SlideShowEvent.PLAY, slideshow_event);
_controls.addEventListener(SlideShowEvent.PAUSE, slideshow_event);
_controls.addEventListener(SlideShowEvent.NEXT_IMAGE, slideshow_event);
_controls.addEventListener(SlideShowEvent.PREVIOUS_IMAGE, slideshow_event);
addChild(_controls);
}
Here is how I dispatch and event.[>
Here is how I get a value from the Event’s data.
- * is used to tell the compiler not to type a variable. Its good to avoid compiler errors when you are not sure what kind of data type will be put inside of the variable. [↩]












Leave a Reply