Redispatching Custom Events in AS3
Monday 21 January 2008 - Filed under Flash
Another one of those “I’ll blog this so 6 months from now, when I run into this again, I’ll remember that I blogged something about this and search my own blog for the answer” posts.
I ran into this last week, redispatching a custom event that caused all kinds of problems. After I found the solution, I remember someone told me about this months ago.
clone () method
public function clone():Event
Duplicates an instance of an Event subclass.Returns a new Event object that is a copy of the original instance of the Event object. You do not normally call clone(); the EventDispatcher class calls it automatically when you redispatch an event—that is, when you call dispatchEvent(event) from a handler that is handling event.
The new Event object includes all the properties of the original.
When creating your own custom Event class, you must override the inherited Event.clone() method in order for it to duplicate the properties of your custom class. If you do not set all the properties that you add in your event subclass, those properties will not have the correct values when listeners handle the redispatched event.
In this example, PingEvent is a subclass of Event and therefore implements its own version of clone().
[as]class PingEvent extends Event {
var URL:String;public override function clone():Event {
return new PingEvent(type, bubbles, cancelable, URL);
}
}[/as]Returns
Event — A new Event object that is identical to the original.
See alsoEvent objects
2008-01-21 » keith
21 January 2008 @ 1:41 pm
Might be a good Idea to make an event that extends clone that dynamically loops through properties and sets them…that you can extend from
21 January 2008 @ 2:27 pm
it’s not just the properties, you have to have clone return the correct type. i suppose you could do that dynamically by finding the class and making an instance of it, but the clone method will usually be only a single line anyway: return new MyCustomEvent(params…); Easy enough to just get in the habit of adding that.
22 January 2008 @ 9:39 am
eclipse templates to the rescue…
9 April 2008 @ 12:42 pm
[...] Flex framework and the sample applications. If you don’t override clone, your custom Event won’t be redispatched correctly. This could lead to a type coercion error if you’re lucky. In worse cases, it might fail [...]
15 December 2008 @ 11:29 am
Just saved me from a night head-ache. I remember reading something about this stuff long time ago, and now when I had trouble with it myself the problem was finding the solution.
Thanks Keith and Google Reader.:)
14 July 2009 @ 11:05 am
Thank you! You saved me at least an hour of debugging.
28 August 2009 @ 3:13 pm
Thanks Keith! I loving your site more and more.