Custom AS3 Events – Personal Notes

Posted by David Jumeau
Oct 20 2010

Every time when I consider using custom events I have to scour the web for it. So I am writing my personal notes for it.

Here is a good link about forming your custom event:

http://www.charglerode.com/blog/?p=51

Robert Penner also posts his observations on event handling from the Flash community.

One important aspect is the requirement of overriding the clone method (via Keith Peters.) Ben Clinkinbeard quotes on Robert’s post : “clone() is only called if an event is manually re-dispatched by passing it to dispatchEvent() again. So if a parent catches it and then does dispatchEvent( childEvent ), clone() will be used and required. Bubbling alone does not call clone(), but overriding it is good practice.”

My observation is that I have been getting errors in Flash Builder regarding to the order of parameters. So by adding new arguments after all the default arguments would give me errors. This was resolved when I added my new arguments after the “type” argument. So here is a code snippet.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
package myFilePathToEventClass
{
 
  import flash.events.Event;
 
  public class MyCustomEvent extends Event
  {
    //Add Custom Event ids here
    static const SOMEEVENT:String = "someEvent";
   
    //Add public properties here (whatever data type) ... will be available in the event handler
    public param1:String;
    public param2:Object;
   
    public function MyCustomEvent(type:String,
                param1:String,
                param2:Object,
                bubbles:Boolean = false,
                cancelable:Boolean = true )
    {
      super(type, bubbles, cancelable);
      this.param1 = param1;
      this.param2 = param2;    
    }
   
    override public function clone():Event {
      return new MyCustomEvent(type, param1, param2, bubbles, cancelable);
    }
   
    override public toString():String {
      return formatToString("MyCustomEvent", "type", "param1", "param2", "bubbles", "cancelable");
    }
   
  }
 
}

3 Responses

  1. David Jumeau says:

    Found a bug in the code in line number 27.

    It requires a “new” key word.

    Without it causes this error:

    Incorrect number of arguments. Expected no more than 1.

  2. Simon says:

    Hey David, you should not specify :void on your constructor. Also, if you only have only on event type on your class, you can just call super(SOMEEVENT).
    You also have a typo in the argument list, there shouldn’t be a semicolon after the last argument. I would be surprised if this code compiles at all.

  3. David Jumeau says:

    Thanks Simon. Thanks for the sharp eye. You rock!

*
To prove you're a person (not a spam script), type the security word shown in the picture. Click on the picture to hear an audio file of the word.
Click to hear an audio file of the anti-spam word

Trackback URL for this entry