所有Event對象都有target和currentTarget屬性,target屬性可引用事件分派對象,currentTarget屬性可引 用正在被檢測事件監聽器的當前節點。也就是說target當前你點擊組件,currentTarget表示你註冊了監聽器的組件.
在事件將在控件鏈中向上冒泡,在此過程中target始終不變,currentTarget在每個向上移動的過程中及時改變。
例如當用戶點擊一個Button控件,很可能事件派發者是Button的內部子組件UITextField,事件向上冒泡過程中target始終爲
UITextField不變,但currentTarget會逐步冒泡到Button組件,這時,觸發了在Button上監聽的Click事件處理函數。
綜上,開發人員一般使用event.currentTarget屬性,event.target屬性很少使用。
測試:
- <?xml version= "1.0" encoding= "utf-8" ?>
- <mx:Application xmlns:mx="http://www.adobe.com/2006/mxml" layout= "absolute" initialize= "init();" >
- <mx:Script>
- <![CDATA[
- import mx.controls.Alert;
- private function canvasClick(event:MouseEvent):void{
- Alert.show('canvas target:' +event.target.id);
- Alert.show('canvas currentTarget:' +event.currentTarget.id);
- }
- private function panelClick(event:MouseEvent):void{
- Alert.show('panel target:' +event.target.id);
- Alert.show('panel currentTarget:' +event.currentTarget.id);
- //event.stopImmediatePropagation();
- }
- private function init():void {
- _canvas.addEventListener(MouseEvent.CLICK,canvasClick);
- _panel.addEventListener(MouseEvent.CLICK,panelClick);
- }
- ]]>
- </mx:Script>
- <mx:Canvas x="0" y= "0" width= "100%" height= "100%" backgroundColor= "#FDFCFC" id= "_canvas" >
- <mx:Panel x="116" y= "64" width= "427" height= "293" layout= "absolute" id= "_panel" >
- <mx:Button x="188" y= "158" label= "Button" id= "_click" />
- <!-- image這個組件無法產生click事件 -->
- <mx:Image source="1.png" id= "_image" x= "125" y= "70" width= "102" height= "47" />
- </mx:Panel>
- </mx:Canvas>
- </mx:Application>
總結:
(1)button這個組件默認的已經註冊了click事件,image沒有註冊,必須手動註冊click事件
(2)只有子組件的事件觸發了,纔會觸發父組件的,否側不會觸發事件(事件的傳播性,從 子----> 父)
(3)event.stopImmediatePropagation();這個方法是停止事件向父組件傳播的