谁能告诉我flex中target和currenttarget之间的区别?
3 回答
当然,我也遇到了一些麻烦。该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
这是一个简单的显示对象树,当应用程序准备好时,我:
- 在树中的每个组件上为同一事件添加侦听器。
- 调度任意事件(仅用于演示)。我选择了
Event.COMPLETE
。
由于所有事物都为同一事件注册了一个 eventHandler,并且由于我已设置bubbles
为 true ( new Event(type, bubbles)
),因此树中的任何事物,从 child 到 greatGrandParent 及其他,为 注册了事件处理程序Event.COMPLETE
,都将运行该方法completeHandler
:事件沿链向上传播,然后返回。Thetarget
是发送事件的那个,所以既然child
发送了它,它就应该是常量。这currentTarget
就是变化。
这意味着,假设您想检查何时滚动 Flex 中的 DataGrid,您想知道何时滚动 DataGrid 中的 itemRenderer 之一内的 Checkbox。一种方法是在每个 itemRenderer 的复选框上为MouseEvent.ROLL_OVER
. 另一种方法是将EventListener 添加到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
。
希望有帮助,兰斯
在提出这样的问题之前,您应该阅读以下网站上的教程:http: //www.adobe.com/devnet/flex/videotraining/以了解 Flex 的介绍。第 1 天就涵盖了您的问题。