January 4, 2007

Propogating Events in Flex 2.0

It’s time for another JB explains how to solve a frustrating problem so you can find the answer on Google

Problem:

I’m writing a Flex 2.0 app, and I need to propogate an event from a low level class back to the top level app.

  1. I create a new Event subclass, and add a listener for the appropriate type in my app
  2. I set up a button so it fires the event.
  3. I run the app and click the button.
  4. Nothing happens

I sigh, and look at the Flex examples.  Right there, in the help/tutorials, they show how you can fire a MouseEvent and catch it, exactly how I want to do it.

  1. In a fit of inspiration, I change my custom event into a MouseEvent, leaving everything else unchanged
  2. It works!

Well, let’s try again with a plain vanilla Event.  No Joy.

Finally, in a fit of inspiration, I set up the debugger and inspect the contents of a regular Event and a MouseEvent.   Sure enough, in MouseEvent, bubbles == true.

  1. Curious, I modify the plain Vanilla event, and make sure that bubbles == true.
  2. It works

Ah hah! I update my custom event, set bubbles = true in the constructor, and put it back into the code.  Everything works.  Boo Yah.

The moral of the story:  Your event needs to set bubbles == true if you want to catch it in a separate class from where you fire it.
Note: I have no idea what the negative side effects of setting bubbles == true are.   But it seems to work well for what I need.