Your own event in Flash AS3

Want to create an event of your own that can be raised and handled like the build in Flash? Well then you've landed on the right page. So here we go!

First create your new event class, which extends flash.events.Event:
package {
import flash.events.Event;

public class MyEvent extends Event {
// Types of events that could be casted:
public static const HUNGRY:String = "hungry";
public static const HAPPY:String = "happy";
public static const SAD:String = "sad";

public function MyEvent(type:String, bubbles:Boolean = false, cancelable:Boolean = false){
super(type, bubbles,cancelable);
}
}
}

Now you can setup event listeners for your new event:
// more code above ..

addEventListener(MyEvent.HUNGRY, goEatSome);

// more code below ...


public function goEatSome(e:MyEvent) {
// more code ...
}

And finally, we need to dispatch the event:
dispatchEvent(new MyEvent(MyEvent.HUNGRY));

Not that hard :)

If you want to pass more variables with your event just add them to your event class and add them to the constructor, like this:
package {
import flash.events.Event;

public class MyEvent extends Event {
// Types of events that could be casted:
public static const HUNGRY:String = "hungry";
public static const HAPPY:String = "happy";
public static const SAD:String = "sad";
public var linesOfCodeWritten:int;

public function MyEvent(linesOfCode:int, type:String, bubbles:Boolean = false, cancelable:Boolean = false){
super(type, bubbles,cancelable);
linesOfCodeWritten = linesOfCode;
}
}
}

And you read your variable with e.linesOfCodeWritten in your event handler.

Related posts:

Comments

comments powered by Disqus