I'm new to Adobe Flex, and am working on a desktop Air application. The jist of my problem is figuring out how a child component can be aware of one of its parents properties. The parent might be more than one level up.
Here's a simplified example to illustrate.
I have a custom component that is made up of a few child components, in the example there is only a single button. I have several instances of this custom component next to each other. When one of the child buttons is pressed, I want to generate an event that lets another part of my application know which instance of the custom component the button belonged to. I understand how to create custom events, so I left that part out of the sample code.
My current approach involves creating a property, (e.g. a "position" integer) that I assign to each of the parent components in mxml. The children components also have the position property, which is set to match the parent when the "preinitialize" event occurs. According to the component lifecyle, the preinitialize event occurs in parent components first, then goes down the line of children. Is this safe? Or is there a better way to do this?
Using data binding seems a waste of resources, because the position property never changes after the application loads.
Here are some relevant code snippets.
main.mxml
<s:VGroup>
<components:CustomComponent position="0"/>
<components:CustomComponent position="1"/>
<components:CustomComponent position="2"/>
</s:VGroup>
CustomComponent.mxml
<fx:Script>
<![CDATA[
[Bindable]
public var position:int;
]]>
</fx:Script>
<components:CustomButton
preinitialize="(event.target as CustomButton).setPosition(position)"/>
CustomButton.mxml
<s:Button>
<fx:Script>
<![CDATA[
public var position:int;
public function setPosition(position:int):void
{
this.position = position;
}
]]>
</fx:Script>
</s:Button>
"how a child component can be aware of one of its parents properties."
The parent might be more than one level up. -> Then it is not a parent, but an ancestor. You might need to go up the parent chain. this.parent.parent.
Also look into this.document and this.owner. For list based controls these mean different things.
Finally, Look into event bubbling. Sounds like you want your events to bubble up to your top level container.