Saturday, July 6, 2013

Playing with MouseEvent in Flex 3

I have come across a very interesting problem while developing a flex application where I have a
button control and I want to call two different functions on  click of the button . The interesting part
is that I want to call two different functions on different events of the same button control, one at
single click and other at double click .
Now what to do in this case as it will always execute the function defined at single click .
So what I am gonna do is to use a Timer using setInterval( ) method and use it to solve this problem.
The code goes here -
<?xml version="1.0" encoding="utf-8"?>
<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml" layout="absolute">
<mx:Script>
<![CDATA[
import mx.controls.Alert;
import flash.utils.clearInterval;
private var timeGap:Number = new Number();
private function doubleClick(event:MouseEvent):void {
clearInterval(timeGap);
//put your code here to be executed on double click
Alert.show("double click");
}
private function singleClick(event:MouseEvent):void {
clearInterval(timeGap);
timeGap = setInterval(otherClick, 250);
}
private function otherClick():void {
//put your code here to be executed on single click
Alert.show("first click");
clearInterval(timeGap);
}
]]>
</mx:Script>
<mx:Button label="click" x="134" y="94"
click="singleClick(event)"
doubleClickEnabled="true"
doubleClick="doubleClick(event)"/>
</mx:Application>
Now it’s the time to explain whats going on inside the code.
On single click and double click events I am invoking two different Alerts to just display a message,
In your case you can write any code which is to be executed on those click events.
On click, inside the singleClick( ) method, we will reset & initiate the timer which will call the
otherClick( ) method on complete. otherClick( ) method contains actual single Click code.
If doubleClick is not invoked, then the  timer completes and otherClick( ) method is executed.
But if doubleClick is invoked , it will call the doubleClick( ) method, where we will clear the
timer so the timer will not complete and execute the otherClick( ) method  and thus it will invoke the
doubleClick( ) method. - Full Post

No comments:

Post a Comment