开发者

Type cast error in dispatchEvent

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 {
        removeEventListene开发者_开发知识库rs();
        var newEvent:SomeEvent = event.clone(); //create a clone of itself
        dispatchEvent(newEvent);
 }

Can anyone help me on this? Thank you.


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_US/AS3LCR/Flash_10.0/


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜