views:

74

answers:

2

I have three classes: A, B, C. class A dispatches a event, class B will handle this and then dispatch it C. However, I got this weird type casting error in B's dispatchEvent function, which looks like follows:

 public function handler(event:SomeEvent):void {
        removeEventListeners();
        dispatchEvent(event);
 }

If I change it to the following, then I don't get any error:

 public function handler(event:SomeEvent):void {
        removeEventListeners();
        var newEvent:SomeEvent = event.clone(); //create a clone of itself
        dispatchEvent(newEvent);
 }

Can anyone help me on this? Thank you.

+3  A: 

Are you using a custom event? If you are, then you need to define the clone method. When you "re-dispatch" an event flash automatically clones the event and dispatches the clone. That's why when you changed your code to event.clone() it works. So, in a nutshell, your second implementation is correct.

If you don't want to have to write that extra bit of code you should implement the clone method. The documentation of EventDispatcher.dispatchEvent() explains this: http://help.adobe.com/en%5FUS/AS3LCR/Flash%5F10.0/

heavilyinvolved
A: 

You could do this.

public function handler(event:SomeEvent):void {
    removeEventListeners();
    dispatchEvent(event.clone);
 }

You need to clone the event. Once they are dispatched they can't be re-dispatched unless cloned. I am not sure why this is, perhaps something to do with handlers getting into infinite loops.

As heavily Involved stated you should implement a clone method on your event if it's custom. All this needs to do is return a new event of your type, copying any state/variables.

robmcm