« No Entry Today | Main | The Circus is Coming to Town »

Events in Flex 2

Today I got a familiar error while working with some event code:

TypeError: Error #1034: Type Coercion failed: cannot convert flash.events::Event@35f04c1 to com.neophi.events.CustomEvent.

The short answer is that this error results from failing to implement a clone() method on a custom event class. The long answer is that most of the time not implementing a clone() method won't hurt you, based on how you use your custom events, but you really should create one. In fact the Actionscript 3 (AS3) documentation is pretty clear about this:

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.

This is a time that I wish AS3 had abstract methods.

Why I say you don't really need a clone() method is that it only becomes an issue if you relay an event. The follow code is an example of event relaying:

private function relay(customEvent:CustomEvent):void
{
    dispatchEvent(customEvent);
}

In this case an event listener redispatches the event that it got. When this happens the event framework behind the scenes calls the clone() method to create a new instance of the event. If you don't have a clone() method and the next listener in the chain is expecting an instance of CustomEvent, the error from above happens. If instead that same listener was only expecting an instance of the Event class, it would work, but any additional information contained in CustomEvent class would be lost, including the ability to cast it to an instance of CustomEvent.

In most cases the clone() method is simple to implement; just transfer any constructor arguments to a new instance of the class. Something like:

override public function clone():Event
{
    return new CustomEvent(_message);
}

Based on the type of event you will probably have more arguments including the all important type and often the other standard event variables for bubbling and cancelability.

While I'm on the subject of events I'll also talk about Event metadata or annotations that you can apply to classes. Often if you have an AS3 class that can emit custom events you will add metadata like this at the top:

package com.neophi {
    import com.neophi.events.CustomEvent;

    import flash.events.EventDispatcher;

    [Event(name="customChange", type="com.neophi.events.CustomEvent")]

    public class EventSource extends EventDispatcher {
        // class code removed 
    }
}

The thing to keep in mind is that depending on how this class will be used you probably don't need that metadata. If this AS3 class isn't used in MXML you can skip the metadata. The metadata is only used to inform the compiler how to translate an MXML event attribute into the appropriate code.

For example with the above class and metadata you could use it in MXML like this:

<?xml version="1.0" encoding="utf-8"?>
<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml" layout="vertical" xmlns:neophi="com.neophi.*">
<mx:Script>
<![CDATA[
import com.neophi.events.CustomEvent;

private function customChanged(customEvent:CustomEvent):void
{
    output.text += "EventTest: " + customEvent + "\n";
}
]]>
</mx:Script>
<neophi:EventSource id="eventSource" customChange="customChanged(event);" />
<mx:Button label="Go" click="eventSource.source();"/>
<mx:TextArea id="output" width="100%" height="400"/>
</mx:Application>

Because cutomChange is defined in the metadata for the EventSource class, in MXML you can now assign a handler to that event. In this case the method customChanged will be called whenever our instance of EventSource dispatches that event.

The method the button is calling to cause eventSource to fire the event is:

public function source():void
{
    var customEvent:CustomEvent = new CustomEvent("Event Message");
    dispatchEvent(customEvent);
}

This code is part of the EventSource class listed above. A new instance of CustomEvent is created and then dispatched. At this point all listeners will get called.

If you tried instead to assign the customChange handler in MXML without the metadata in EventSource you would get a compile error like this:

Cannot resolve attribute 'customChange' for component type com.neophi.events.EventSource.

For events then the two rules of thumb are:

  1. always create a clone() method in any custom event class
  2. add event metadata if you will need to setup handlers for that event in MXML

Tags: actionscript3 as3 events flex programming

Comments

Thanks - v useful.
thank u very much Daniel... i was wondering y i was getting a "Type Coercion failed" run time error about custom events. after implementing clone method in custom event, its running smoothly :)
Nice one, I often conveniently forget to override clone() in my Event subclasses, I really shouldn't. Regarding the [Event(*)] metadata-tag though, I always try to keep 'em in there, as ASDoc uses them to gather information about which Events are dispatched by a class. Of course this only goes for projects for which you actually want to generate ASDocs..
Thanks for this very useful write-up.
Thanks for explaining clone and metadata in layman terms...now I will never forget when and why to use them... cheers, ravi
Just wanted to add something to this info... I had the same issue but it turned out the definition I gave to my custom event types (ie: CHANGE, UPDATE whatever) were reserved internal names. I didn't realize that the event system interpreted those values independent of the namespace. For example, I when it reads Event.CHANGE the string value is "change"... it doesn't matter that that constant is contained within the Event class, if you define CustomEvent.CHANGE == "change", the event system will read your custom event as being Event.CHANGE and throw a coercion error. Yeah so, as blatant and obvious as that is... it held me up for about 2 hours before I clued in. Hope that is helpful!