I have a main application which has an int variable declared. I want to access this variable in another component which is present in another package. How can I do this?
Main.mxml (default package)
<s:Application xmlns:fx="http://ns.adobe.com/mxml/2009"
xmlns:s="library://ns.adobe.com/flex/spark"
xmlns:mx="library://ns.adobe.com/flex/mx"
preinitialize = "foo()">
<fx:Script>
<![CDATA[
public var value1:int;
public function foo():void {
value1 = 5;
}
]]>
</fx:Script>
<\s:Application>
Comp.mxml (components package)
<?xml version="1.0" encoding="utf-8"?>
<s:Group xmlns:fx="http://ns.adobe.com/mxml/2009"
xmlns:s="library://ns.adobe.com/flex/spark"
xmlns:mx="library://ns.adobe.com/flex/mx"
creationcomplete = "foo2()">
<fx:Script>
<![CDATA[
public function foo2(): void{
//------> access value1 from Main.mxml here.
}
]]>
</fx:Script>
</s:Group>
Best Answer
Since the variable you need is in the main application class, you can use the parentApplication property to access it.
In general, the correct way of doing this is to pass a reference of the source object (in this case, the application) to the caller object - or pass the value itself through some public property. Assuming that
Comp
in question is present in the main app itself, you can do: