开始学习Flex,会在别人的代码中经常看到target和currentTarget这两个属性,一般是event.target、event.currentTarget,那他们两个有什么区别呢?
简单说,target是事件的调用对象(event dispatcher),currentTarget是事件的处理对象(event processor)
以一个实例来说吧
?1?<?xml?version="1.0"?encoding="utf-8"?>
?2?<mx:Application?xmlns:mx="http://www.adobe.com/2006/mxml"?layout="vertical"?name="app"
?3?????initialize="init()">
?4?????
?5?????<mx:Button?id="btn"?name="btn"?label="按钮1"/>
?6?????
?7?????<mx:Button?id="btn2"?name="btn2"?label="按钮2"?click="clickHandler(event)"?/>
?8?????
?9?????<mx:Script>
10?????????<![CDATA[
11?????????????import?mx.controls.Alert;
12?????????????private?function?init():?void
13?????????????{
14?????????????????addEventListener(MouseEvent.CLICK,?clickHandler);?????????????????
15?????????????}
16?????????????
17?????????????private?function?clickHandler(event:?MouseEvent):?void
18?????????????{
19?????????????????Alert.show("target:?"?+?(event.target?as?DisplayObject).name
20?????????????????????+?"\ncurrentTarget:?"?+?(event.currentTarget?as?DisplayObject).name);
21?????????????}
22?????????]]>
23?????</mx:Script>
24?</mx:Application>
25?
?2?<mx:Application?xmlns:mx="http://www.adobe.com/2006/mxml"?layout="vertical"?name="app"
?3?????initialize="init()">
?4?????
?5?????<mx:Button?id="btn"?name="btn"?label="按钮1"/>
?6?????
?7?????<mx:Button?id="btn2"?name="btn2"?label="按钮2"?click="clickHandler(event)"?/>
?8?????
?9?????<mx:Script>
10?????????<![CDATA[
11?????????????import?mx.controls.Alert;
12?????????????private?function?init():?void
13?????????????{
14?????????????????addEventListener(MouseEvent.CLICK,?clickHandler);?????????????????
15?????????????}
16?????????????
17?????????????private?function?clickHandler(event:?MouseEvent):?void
18?????????????{
19?????????????????Alert.show("target:?"?+?(event.target?as?DisplayObject).name
20?????????????????????+?"\ncurrentTarget:?"?+?(event.currentTarget?as?DisplayObject).name);
21?????????????}
22?????????]]>
23?????</mx:Script>
24?</mx:Application>
25?
说明:
- 点击btn,btn是事件发送者,因此,target是btn;
- app注册了事件监听器,用于监听MouseEvnet.Click事件,是事件处理者,因此currentTarget是app
- btn2自己注册了click事件,那么btn2既是事件发送者,又是处理者,因此,target和currentTarget都是btn2,这种情况下,两者是一致的
- 同时注意,由于app注册了鼠标点击事件,在点击btn2的时候,首先响应的是app的处理器,然后才是btn2的处理器