views:

55

answers:

4

I have a public variable set within fx:Script tags in a parent component that I'd like to access directly from a child component. How can I do this? I don't want to pass the variable to the child component (I know how to do this and am currently using this approach). Following is a simplified version of the mxml:

Note: SimpleComp is an HBox with a couple of lists.

<mx:Accordion>
    <comp:SimpleComp/>
</mx:Accordion>
+1  A: 

You could use event to communicate, in that sense Signals can be a pretty good approach http://www.peterelst.com/blog/2010/01/22/as3-signals-the-best-thing-since-sliced-bread/

PatrickS
+1  A: 

In your desire to directly access a public variable in a different class arbitrarily without employing another design pattern you're sort of breaking encapsulation principles. If it's a one time thing, you can just define your child component to take a reference to its parent on instantiation.

If you need to do this a lot, there is an excellent implementation of Apple's NSNotificationCenter in AS3 defined here: http://www.archer-group.com/development/mimicking-cocoas-nsnotificationcenter-in-actionscript-3 that will allow your objects to communicate with each other more robustly and appropriately.

Tegeril
A: 

You can do the following in the code of your SimpleComp component:

var parent:Accordion = this.parent as Accordion;

to have an access to all parent's public fields.

But that is not good style, as already mentioned above.

Mb you should consider some event dispatching mechanism or using mvc frameworks like PureMVC.

Tatyana Maximovskaya
A: 

Hmm not sure what you are after, but maybe outerDocument is what you are after

e.g.

<mx:DataGrid>
    <mx:columns>
        <mx:DataGridColumn>
            <mx:itemRenderer>
                <fx:Component>
                    <s:MXDataGridItemRenderer autoDrawBackground="false">
                        <fx:Script>
                            <![CDATA[
                                public function action():void
                                {
                                    trace(outerDocument.fooBar);
                                }
                            ]]>
                        </fx:Script>
                        <s:states>
                            <s:State name="normal" />            
                            <s:State name="hovered" />
                            <s:State name="selected" />
                        </s:states>
                    </s:MXDataGridItemRenderer>
                </fx:Component>
            </mx:itemRenderer>
        </mx:DataGridColumn>
    </mx:columns>
</mx:DataGrid>
butterbrot