flex中target和currenttarget有什么区别?

pra*_*nth 9 apache-flex actionscript event-handling actionscript-3 event-delegation

任何人都可以告诉我flex中的target和currenttarget之间的区别吗?

Lan*_*ard 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>
Run Code Online (Sandbox Code Playgroud)

产量

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
Run Code Online (Sandbox Code Playgroud)

它是一个简单的显示对象树,当应用程序准备就绪时我:

  1. 在树中的每个组件上添加同一事件的侦听器.
  2. 派遣任意事件(仅用于演示).我选择了Event.COMPLETE.

因为所有事件都为同一个事件注册了一个eventHandler,并且因为我已经设置bubbles为true(new Event(type, bubbles)),所以树中的任何东西,从child到greatGrandParent以及已经注册了事件处理程序Event.COMPLETE,将运行该方法:completeHandler.事件沿着链条向上移动然后向下移动.该target是调度该事件的一个,这样以来child派出它,它应该是恒定的.这currentTarget是什么变化.

这意味着,假设您要检查何时在Flex中滚动DataGrid,您想知道何时在DataGrid中的某个itemRenderer内滚动Checkbox.一种方法是在每个itemRenderer的复选框上添加EventListener MouseEvent.ROLL_OVER.另一种方法是将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!");
}
Run Code Online (Sandbox Code Playgroud)

这就是我经常使用的方式event.target.

希望有所帮助,兰斯