Reputation: 4750
Given the following code:
Class CEvent:
public class CEvent extends Event
{
public static const TYPE:String = "cEvent";
private var m_strCode:String;
public function get code():String
{
return m_strCode;
}
public function CEvent(pCode:String, bubbles:Boolean=false,
cancelable:Boolean=false)
{
super(TYPE, bubbles, cancelable);
m_strCode = pCode;
}
}
Class A:
dispatchEvent(new CEvent(MY_CONST))
Class B:
m_a = new A();
m_a.addEventListener(CEvent.TYPE, onCEvent);
.
.
.
private function onCEvent(pEvent:CEvent):void
{
switch (pEvent.code)
{
case A.MY_CONST:
dispatchEvent(pEvent);
}
}
Class C:
m_b = new B();
m_b.addEventListener(CEvent.TYPE, onCEvent);
.
.
.
private function onCEvent(pEvent:CEvent):void
{ // breaks right here
}
I get this error when it breaks on class C, after dispatching it originally from Class A:
Error #1034: Type Coercion failed: cannot convert flash.events::Event@9861089 to
<path>.CEvent.
This doesn't seem to make a lot of sense, and it seems to be going completely against the way inheritance works. Even if there were code in Adobe's implementation of dispatchEvent() that specifically goes through and shaves off anything that's been added through inheritance and just dispatches a "normal" Event instance, that should cause it to break in class B, not C.
Could someone please explain? Thanks.
Edit: By the way changing class B's code to do this instead makes everything work just fine:
dispatchEvent(new CEvent(pEvent.code));
I still need to understand what the issue is though. Thanks.
Upvotes: 0
Views: 72
Reputation: 18193
The error occurs because you have not implemented the clone()
method in your custom event.
When you re-dispatch an event (in your Class C), Flash clones the event instead of just re-dispatching the original event.
The event that is re-dispatched therefore is a plain old Event
object, because that's what the default clone()
method returns.
In general, you should always implement a clone()
method for your custom events. It's pretty straight forward to do. In this case it should look something like this:
override public function clone():Event
{
return new CEvent(m_strCode, bubbles, cancelable);
}
Upvotes: 6