2010-02-19 35 views
1

是否有可能根據事件偵聽器確定哪個對象調用函數?例如,我有2個按鈕在舞臺上,當他們被點擊時調用相同的功能。我想要確定哪個按鈕是發件人的函數。Actionscript 3.0確定事件監聽器發件人?

firstButton.addEventListener(MouseEvent.CLICK, myFunction); 
secondButton.addEventListener(MouseEvent.CLICK, myFunction); 

function myFunction(e:MouseEvent):void 
{ 
var myString:String = "The button that called this function was (??)"; 
trace(myString); 
} 

回答

5

Event

function myFunction(e:MouseEvent):void { 
var myString:String = "The button that called this function was "+e.currentTarget; 
trace(myString); 
} 
+1

當你想要原始的發送者'目標'更好,如果事件冒泡currentTarget將是你捕捉它時的事件。 – grapefrukt 2010-04-17 11:18:49

1

內myfunction的使用屬性currentTarget,e.currentTarget要堅持發送事件的按鈕的引用。

1

我只想補充到:在你的功能得到了事件對象有兩個屬性,有時可能會造成混淆他們之間的區別:

e.target - 目標總是會回報給你該事件的原始調度員,所以如果你點擊了一個按鈕,但在收聽父母時,你的目標仍然是按鈕。

e.currentTarget - currentTarget返回您從事件或adobes語言中詢問的對象「正在使用事件偵聽器主動處理Event對象的對象。」。

所以你的當前目標和目標可以產生不同的結果,你需要牢記這一點。 p.s.如果你的事件不起泡(非可視/非用戶交互鼠標事件),那麼你的currentTarget和target將是相同的,或者如果你問到在發生冒泡事件的情況下派發事件的對象。