回答

18

当然,我也遇到了一些麻烦。 currentTarget属性是您为其注册事件处理程序的IEventListener。 target是分派您正在处理的事件的人。所以currentTarget更改,target不。

看看下面的例子:

示例应用程序

<?xml version="1.0" encoding="utf-8"?> 
<mx:Application 
    xmlns:mx="http://www.adobe.com/2006/mxml" 
    creationComplete="addListeners()"> 

    <mx:Script> 
     <![CDATA[ 

      protected function addListeners():void 
      { 
       greatGrandParent.addEventListener(Event.COMPLETE, completeHandler); 
       grandParent.addEventListener(Event.COMPLETE, completeHandler); 
       aParent.addEventListener(Event.COMPLETE, completeHandler); 
       child.addEventListener(Event.COMPLETE, completeHandler); 
       // dispatch event that "bubbles", second param is "true" 
       // dispatched from child 
       child.dispatchEvent(new Event(Event.COMPLETE, true)); 
      } 

      protected function completeHandler(event:Event):void 
      { 
       trace("target: ", event.target + ", currentTarget: ", event.currentTarget); 
      } 

     ]]> 
    </mx:Script> 

    <mx:Panel id="greatGrandParent"> 
     <mx:Panel id="grandParent"> 
      <mx:Panel id="aParent"> 
       <mx:Button id="child"/> 
      </mx:Panel> 
     </mx:Panel> 
    </mx:Panel> 

</mx:Application> 

输出

target: MyApp.greatGrandParent.grandParent.aParent.child, currentTarget: MyApp.greatGrandParent.grandParent.aParent.child 
target: MyApp.greatGrandParent.grandParent.aParent.child, currentTarget: MyApp.greatGrandParent.grandParent.aParent 
target: MyApp.greatGrandParent.grandParent.aParent.child, currentTarget: MyApp.greatGrandParent.grandParent 
target: MyApp.greatGrandParent.grandParent.aParent.child, currentTarget: MyApp.greatGrandParent 

这是显示目标的简单树,当应用程序已经准备好我:

  1. 为树中每个组件上的相同事件添加侦听器。
  2. 发送任意事件(仅供演示)。我选择了Event.COMPLETE

既然一切都已经注册的事件处理程序对于同一事件,因为我已经设置bubbles为true(new Event(type, bubbles)),什么树,从小孩到greatGrandParent和超越,已注册的事件处理程序Event.COMPLETE,将运行该方法:completeHandler。事件沿着链条传播,然后回落。 target是派遣该事件的人,因此child派遣它,它应该是不变的。 currentTarget是什么改变。

这意味着,假设您想要检查何时在Flex中的DataGrid上滚动,您想知道何时滚动DataGrid中的某个itemRenderer内的复选框。一种方法是在每个itemRenderer的复选框上为MouseEvent.ROLL_OVER添加EventListener。另一种方法是在对addEventListener到DataGrid本身MouseEvent.ROLL_OVER,检查一下目标是对事件:

protected function dataGrid_rollOverHandler(event:MouseEvent):void 
{ 
    // event.currentTarget is DataGrid 
    if (event.target is CheckBox) 
     trace("rolled over checkbox!"); 
} 

那怎么我经常使用event.target

希望帮助, 兰斯