I am trying to write a code to differentiate between simgle and double clicks using GWT and GWTQuery. I got the idea here. So I translated it into GWT like this: (my app can't have global variables, so I am doing that part with element attributes instead):
$("img").live("click", new Function() {
public boolean f(Event event) {
String clicksString = $(event).attr("clicks");
int clicks = Integer.parseInt(clicksString);
clicks++;
$(event).attr("clicks",String.valueOf(clicks));
Timer t = new Timer() {
@Override
public void run() {
Window.alert("Click");
$(event).attr("clicks","0");
}
};
if (clicks == 1) {
t.schedule(200);
}
else {
t.cancel();
$(event).attr("clicks","0");
Window.alert("Double Click");
}
return true;
}
});
Here, when the image is clicked, an alert should pop up showing Single Click, and if the user double clicks (within 200 ms), it should pop up Double Click. It works fine for the single click, but on double click, even though the Double Click alert pops up, on clicking Ok to get rid of it, I find the Single Click alert waiting to be get rid of.
Somehow, I think the t.cancel()
is not firing on double-click. Can anyone tell me how to fix this?
Update:
The accepted solution works fine for alerting, but when I need the event
parameter as well, it has to be slightly tweaked. After doing that, again, the problem comes back, the timer is not cleared, and now I get two alerts, Double Click and Click..:
$("img").live("click", new Function() {
int clicks = 0;
public boolean f(Event event) {
Timer t = new Timer() {
@Override
public void run() {
clicks = 0;
// Here I need the event paramater
}
};
if (clicks++%2 == 0) {
t.schedule(5000);
}
else {
t.cancel();
clicks = 0;
// Here also I need the event paramater
}
return true;
}
});
Updated by @Manolo: Based on my comment below last code should be:
$("img").live("click", new Function() {
int clicks = 0;
Event event;
Timer t = new Timer() {
@Override
public void run() {
// Use the event
event....
}
};
public boolean f(Event event) {
this.event = event;
if (clicks++%2 == 0) {
t.schedule(5000);
} else {
t.cancel();
// Use the event
event....
}
return true;
}
});