target和currentTarget屬性比較

所有Event對象都有target和currentTarget屬性,target屬性可引用事件分派對象,currentTarget屬性可引 用正在被檢測事件監聽器的當前節點。也就是說target當前你點擊組件,currentTarget表示你註冊了監聽器的組件.

 

在事件將在控件鏈中向上冒泡,在此過程中target始終不變,currentTarget在每個向上移動的過程中及時改變。

例如當用戶點擊一個Button控件,很可能事件派發者是Button的內部子組件UITextField,事件向上冒泡過程中target始終爲 UITextField不變,但currentTarget會逐步冒泡到Button組件,這時,觸發了在Button上監聽的Click事件處理函數。

綜上,開發人員一般使用event.currentTarget屬性,event.target屬性很少使用。

測試:

 

Flex代碼  收藏代碼
  1. <?xml version= "1.0"  encoding= "utf-8" ?>  
  2. <mx:Application xmlns:mx="http://www.adobe.com/2006/mxml"  layout= "absolute"  initialize= "init();" >  
  3.  <mx:Script>  
  4.   <![CDATA[  
  5.    import mx.controls.Alert;  
  6.    private function canvasClick(event:MouseEvent):void{  
  7.     Alert.show('canvas target:' +event.target.id);  
  8.       
  9.     Alert.show('canvas currentTarget:' +event.currentTarget.id);  
  10.    }  
  11.      
  12.    private function panelClick(event:MouseEvent):void{  
  13.     Alert.show('panel target:' +event.target.id);  
  14.       
  15.     Alert.show('panel currentTarget:' +event.currentTarget.id);  
  16.     //event.stopImmediatePropagation();  
  17.    }   
  18.       
  19.    private function init():void {  
  20.     _canvas.addEventListener(MouseEvent.CLICK,canvasClick);  
  21.     _panel.addEventListener(MouseEvent.CLICK,panelClick);  
  22.    }  
  23.   ]]>  
  24.  </mx:Script>  
  25.   
  26.  <mx:Canvas x="0"  y= "0"  width= "100%"  height= "100%"  backgroundColor= "#FDFCFC"  id= "_canvas" >  
  27.   <mx:Panel x="116"  y= "64"  width= "427"  height= "293"  layout= "absolute"  id= "_panel" >  
  28.    <mx:Button x="188"  y= "158"  label= "Button"  id= "_click" />  
  29.    <!-- image這個組件無法產生click事件  -->  
  30.    <mx:Image source="1.png"  id= "_image"  x= "125"  y= "70"  width= "102"  height= "47" />  
  31.   </mx:Panel>  
  32.  </mx:Canvas>  
  33.    
  34. </mx:Application>  
 

總結:

(1)button這個組件默認的已經註冊了click事件,image沒有註冊,必須手動註冊click事件

(2)只有子組件的事件觸發了,纔會觸發父組件的,否側不會觸發事件(事件的傳播性,從 子----> 父)

(3)event.stopImmediatePropagation();這個方法是停止事件向父組件傳播的

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章