Adding custom event in as3 can make life easy. Sometime it needs to set root variable from different class or need to call root function for a specific application. Its better to use custom event than using "root" in class. Its easy to trigger and also can be listen from anywhere. Its make a class independent. Creating custom event handlers in ActionScript 3 is pretty much simple. Here i’m showing a simple myCustomEvent class which extends the flash Event class.
1: //Declare a class for myCustomEvent
2: package wneeds.events{
3:
4: import flash.events.Event;
5:
6: public class myCustomEvent extends Event {
7:
8: public var myMessage:String;
9:
10: public function myCustomEvent(msg) {
11:
12: super("myCustomEvent");
13: myMessage = msg;
14: }
15: }
16: }
In the above class i also declare a variable named "myMessage" to show how to pass variable in a custom event class. For triggering the custom event, it just need to include the class and use the dispatchEvent method as like below…
1: //How to asign a event
2: import wneeds.events.myCustomEvent;
3:
4: dispatchEvent(new myCustomEvent("Hello ..."));
Now time to add Listener to listen the event from anywhere….
1: //How to add the listener for the myCustomEvent..
2:
3: this.addEventListener("myCustomEvent", showMessage);
4:
5: function showMessage(e:myCustomEvent):void {
6: trace(e.myMessage);
7: }
In various purpose its better to pass object. Because in object its easy to pass multiple properties and easy to write in json format.
1: dispatchEvent(new myCustomEvent({name:'tma',height: 100, msg : 'Hello...'}));
Then it can be easily possible to get all the properties from the listener….
Some of my friends want to learn flash. They are searchig for web address where they can found help. So my friends don’t worry here are some flash help sites.. click any and get ur one..