传递引用给MXML组件的属性
前面提的是如何传递值给MXML组件的属性,下面将是传递引用,引用可以是调用中的组件,另一个组件等。
访问Application对象
这个Application对象是一个Flex应用的顶级对象。在你的定制组件中,使用mx.core.Application.application静态属性来引用它。
You can also use the parentDocument property to reference the next object up in the document chain of a Flex application. 这个 parentDocument 成员属性被所有从UIComponet类的组件所继承. For an MXML component, the parentDocument property references the Object corresponding to the component that referenced the MXML component.
更多可参见"使用Application容器"。
例一的定制组件,使用mx.core.Application.application对象来引用:
<?xml version="1.0"?>
<!-- mxmlAdvanced/myComponents/StateComboBoxDirectRef.mxml -->
<mx:ComboBox xmlns:mx="http://www.adobe.com/2006/mxml"
close="handleCloseEvent(event);">
<mx:Script>
<![CDATA[
import flash.events.Event;
import mx.core.Application;
public function handleCloseEvent(eventObj:Event):void {
mx.core.Application.application.myTAMain.text=
String(this.selectedIndex); 直接引用主应用中的myTAMain控件的属性
}
]]>
</mx:Script>
<mx:dataProvider>
<mx:String>AK</mx:String>
<mx:String>AL</mx:String>
</mx:dataProvider>
</mx:ComboBox>
例二:使用parentDocument来引用:
<?xml version="1.0"?>
<!-- mxmlAdvanced/myComponents/StateComboBoxDirectRefParentObj.mxml -->
<mx:ComboBox xmlns:mx="http://www.adobe.com/2006/mxml"
close="handleCloseEvent(event);">
<mx:Script>
<![CDATA[
import flash.events.Event;
public function handleCloseEvent(eventObj:Event):void {
parentDocument.myTAMain.text=String(selectedIndex);
}
]]>
</mx:Script>
<mx:dataProvider>
<mx:Array>
<mx:String>AK</mx:String>
<mx:String>AL</mx:String>
</mx:Array>
</mx:dataProvider>
</mx:ComboBox>
以上两种方法,都需在定制组件中知道被引用对象的某个ID属性,所以说,它跟被引用的组件是紧耦合的,不易被重用。
传递一个引用给组件
在前面一节“定制组件里支持数据绑定”中一样,你也可将一个对象的引用,有数据绑定传递组自定义组件。组件的属性要与被传递的对象是同一种类型吧。
<?xml version="1.0"?>
<!-- mxmlAdvanced/MainPassRefToTA.mxml -->
<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml"
xmlns:MyComp="myComponents.*">
<mx:TextArea id="myTAMain" />
<MyComp:StateComboBoxPassRefToTA outputTA="{myTAMain}" />
</mx:Application>
传递一个引用为调用中组件
<?xml version="1.0"?>
<!-- mxmlAdvanced/CallingComponent.mxml -->
<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml"
horizontalAlign="left"
xmlns:MyComp="myComponents.*">
<!-- Use the caller property to pass a reference to the
calling component to DestinationComp. -->
<mx:Label text="Enter text"/>
<mx:TextInput id="text1" text="Hello"/>
<mx:Label text="Input text automatically copied to MXML component."/>
<MyComp:DestinationComp caller="{this}"/> 将调用中组件this传递给定制组件
</mx:Application>
在定制组件中可以使用:
<?xml version="1.0"?>
<!-- mxmlAdvanced/myComponents/DestinationComp.mxml -->
<mx:VBox xmlns:mx="http://www.adobe.com/2006/mxml">
<mx:Script>
<![CDATA[
// Define variable to reference calling file.
[Bindable]
public var caller:CallingComponent; 这里的caller要声明为调用组件的类型,就是调用组件的文件名哟。
]]>
</mx:Script>
<mx:TextInput id="mytext" text="{caller.text1.text}"/>
</mx:VBox>
注:一个MXML文件对应的便是一个ActionScript类,所以,这个文件名便可当数据类型的使用。