Flex adding an event to call to the parent

So I always have this problem where I'll have a component inside a component, and the parent component needs to do something based on some sort of trigger from the inside component. Using Parent or Application is a big no no, or so my Architect friend tells me ;). They way to do this is create an Event on the inside component. This is pretty easy to do, but I always seem to miss a step and get all frustrated and not understand why it's not working. And in these hot lazy days of summer, it's really not a good motivator. :D

So here are the steps so I can look this up if I forget. I am just going to use a button click as an example, if you need something more intense you'll need to make a custom event.

So... ComponentB is inside ComponentA.

In the actionscript of ComponentB do:

Just below the imports - [Event (name="myEvent", type="flash.events.Event")]

Create a function that dispatches that event:
protected function myFunction():void
{
dispatchEvent(new Event('myEvent'));
}

In the MXML of ComponetB call the function:

<Button id="myButton" click="myFunction()"/>

In the actionscript of ComponentA create a fucntion for what you want the trigger to do:
protected function buttonBClick():void
{
Alert.show("Button in the Panel has been clicked");
}

In the MXML of CompoentA, where you add ComponentB call the event you made:
<ComponentB id="componentB"
myEvent="buttonBClick()"/>

Volia!

Confused? Yeah me too. Here's an example.

Comments

Popular posts from this blog

Flex Advanced Data Grid collapses on refresh

Add and remove lineseries - Flex LineChart

Flex TabNavigator - tab click event?