Flex this
為了便于對(duì)比和敘述,我們先上一段最簡(jiǎn)單的js+html代碼:
<input type="button" value="test" id="htmBtn" οnclick="alert(this.id)">
用慣js+html的程序員都知道,這里的this指向觸發(fā)事件的html組件本身,所以this.id將如愿顯示為”htmBtn”。
但是在flex3中,你寫事件偵聽函數(shù)時(shí),this關(guān)鍵字將指向application,而不再指向觸發(fā)事件本身的組件上了(與js+html完全不同):
例如:
<mx:ComboBox name="ttt"? change="Alert.show('you have change the data!'+this.selectedLabel)">
<mx:dataProvider>
<mx:String>Dogs</mx:String>
<mx:String>Cats</mx:String>
<mx:String>Mice</mx:String>
</mx:dataProvider>
</mx:ComboBox>
中的this.selectedLabel將找不到任何東東。因?yàn)閠his并沒(méi)有指向這個(gè)combobox!!!
那么怎么找到觸發(fā)事件的組件呢?flex提供了event.currentTarget來(lái)指定觸發(fā)事件的當(dāng)前組件,如下方式:
<mx:ComboBox name="ttt"? change="Alert.show('you have change the data!'+event.currentTarget.selectedLabel)">
<mx:dataProvider>
<mx:String>Dogs</mx:String>
<mx:String>Cats</mx:String>
<mx:String>Mice</mx:String>
</mx:dataProvider>
</mx:ComboBox>?
或者:<mx:Script><![CDATA[
private function changeEvt(e:Event):void {
Alert.show('you have change the data!'+e.currentTarget.selectedLabel)"
}
]]></mx:Script>
<mx:ComboBox name="ttt"? change="changeEvt(event)"><mx:dataProvider>
<mx:String>Dogs</mx:String>
<mx:String>Cats</mx:String>
<mx:String>Mice</mx:String>
</mx:dataProvider>
</mx:ComboBox>
官方文檔還提出了特別說(shuō)明,使用event.currentTarget時(shí)有一個(gè)好習(xí)慣可以參考,即,最好先指定好該組件的類型,例如 TextInput(e.currentTarget),這樣做的目的是防止由于該組件某個(gè)屬性不存在時(shí),編譯時(shí)不報(bào)錯(cuò)而運(yùn)行時(shí)才報(bào)錯(cuò),看代碼就明白了:
<?xml version="1.0"?>
<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml">
<mx:Script><![CDATA[
import mx.core.UIComponent;
private function tiHandler(e:Event):void {
/*?
這段代碼將會(huì)在運(yùn)行時(shí)報(bào)錯(cuò),而編譯時(shí)不報(bào)錯(cuò)。因?yàn)門extInput根本沒(méi)有tmesis屬性
e.currentTarget.tmesis = 4;
*/
/*
這段代碼的用法,就能在編譯時(shí)便發(fā)現(xiàn)錯(cuò)誤,不用等到運(yùn)行時(shí)才報(bào)錯(cuò)
TextInput(e.currentTarget).tmesis = 4;
*/
}
]]></mx:Script>
<mx:TextInput id="ti1" click="tiHandler(event)"
text="This is some text. When you click on this control, the first three characters
are selected."/>
</mx:Application>
與50位技術(shù)專家面對(duì)面20年技術(shù)見證,附贈(zèng)技術(shù)全景圖總結(jié)
- 上一篇: 成都大金中央空调售后服务电话是多少?
- 下一篇: 西镁门业的衣柜门是否适合家具定制商使用?