Thursday, December 13, 2012

Distinguish 'double click' from 'click' in Flex

   Defining behavior for both 'click' and 'double click' events in Flex is tricky, as when a double click is done, the click event gets fired. Therefore there needs to be a workaround to solve this issue. First of all add event listeners for 'click' and 'double click' (this can be done either in mxml or actionscrips which I have chosen the later).


//Adding click listener
component.addEventListener(MouseEvent.CLICK, localMouseClickEvent, false, 0, true);

//Adding double click listener
component.addEventListener(MouseEvent.DOUBLE_CLICK, localMouseDoubleClickedEvent, false, 0, true);

//n.b. here component refers to any mx UIComponent 


   According to the code above if a mouse click is issued, 'localMouseClickEvent(MouseEvent)' method is called and for a double click, 'localMouseDoubleClickedEvent(MouseEvent)' should be called. However, when a double click is done, 'localMouseClickEvent(MouseEvent)' triggers.Both functions are defined below. 


/** reference to the deferred click operation */
private var deferredClickReference: Number = 0;


protected function localMouseClickEvent (event: MouseEvent) : void {    
          clearInterval(deferredClickReference); // clearing previous schedule
         
          // defer operation                   
          deferredClickReference = setInterval(deferredMouseClickEvent, 300); 
}
   
protected function deferredMouseClickEvent() : void {
        clearInterval(deferredClickReference); // clearing previous schedule  
        
       // code to execute for 'click'
}

protected function localMouseDoubleClickedEvent(event:MouseEvent):void {
         // revoking deferred click operation
         clearInterval(deferredClickReference);

        // code to execute for 'double click'
}


   The workaround is to defer the single click operations to see if it is actually followed by another click. Another function, 'deferredMouseClickEvent()' is defined, and invoked from localMouseClickEvent(event: MouseEvent0)' scheduled to be triggered after 300 ms. This scheduling is done by 'setInterval(deferredMouseClickEvent, 300)' , which returns a reference to the schedule (this is assigned to 'deferredClickReference'). So if a click is followed by another within 300 ms, double click event operations will be run, otherwise that of click
   'clearInterval(deferredClickReference)' resets the reference, which revokes the scheduled single click operation. This is done before scheduling the deferred operation, after execution of the same and in double click event's function (to prevent deferredMouseClickEvent() run).


 thanks,
Shyarmal.

No comments:

Post a Comment