Saturday, November 8, 2008

Re-dispatching an Event in Flex

There's a trick to re-dispatching a custom event in Flex, and I always forget what it is. Hopefully, I'll remember to look at my own blog the next time I get stuck.

Here are the symptoms this solves: You're dispatching a custom event in one component, then catching that event in another component, only to dispatch it again. But the event never gets to the next component up, which is listening for it.

The reason it's not working is because the flex.events.Event.clone() method is being called when you call dispatchEvent() the second time. All you need to do is override it that function in your custom Event class:


public override function clone():Event{
return new MyEvent(type, mytype1, mytype2, bubbles, cancelable);
}


This fixes the problem every time, and the re-dispatched event will get to the next component. Of course, if you're doing more than two layers of dispatching to get what you want, you may want to consider a better design, but this is useful as a quick hack.