What is the difference between target and currenttarget in flex?

前端 未结 3 2190
悲&欢浪女
悲&欢浪女 2020-12-10 15:41

Can any one please tell me the difference between target and currenttarget in flex?

3条回答
  •  执念已碎
    2020-12-10 16:04

    Sure, I've had some trouble with this too. The currentTarget property is the IEventListener you registered the event handler for. The target is the one that dispatched the event that you are currently handling. So the currentTarget changes, the target doesn't.

    Check out the following example:

    Sample App

    
    
    
        
            
        
    
        
            
                
                    
                
            
        
    
    
    

    Output

    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
    

    It's a simple tree of display objects, and when the app is ready I:

    1. Add listeners for the same event on each component in the tree.
    2. Dispatch an arbitrary event (just for demonstration). I chose Event.COMPLETE.

    Since everything has registered an eventHandler for that same event, and since I have set bubbles to true (new Event(type, bubbles)), anything in the tree, from child to greatGrandParent and beyond, that has registered an event handler for Event.COMPLETE, will run that method: completeHandler. Events travel up the chain then back down. The target is the one that dispatched the event, so since child dispatched it, it should be constant. The currentTarget is what changes.

    This means that, say you want to check when you are rolling over a DataGrid in Flex, you want to know when you roll over a Checkbox inside one of the itemRenderers in the DataGrid. One way is to addEventListener on every itemRenderer's checkbox for MouseEvent.ROLL_OVER. Another way is to addEventListener to the DataGrid itself for MouseEvent.ROLL_OVER, and check what the target is on the event:

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

    That's how I often use event.target.

    Hope that helps, Lance

提交回复
热议问题