import java.util.HashMap;
import com.google.gwt.user.client.Timer;
/**
* The class LastCallBurstEventsMgr takes care of the burst of the same event,
* by skipping the first ones and executing only the last one.
*
* Exemple of usage:
*
*
* scrollPanel_.addScrollListener(new ScrollListener() {
* public void onScroll(final Widget widget, final int scrollLeft,
* final int scrollTop) {
* LastCallBurstEventsMgr.addEvent(new Event("scroll-me-babe",
* new Function() {
* public void execute() {
* System.out.println(" scrollLeft = " + scrollLeft
* + " scrollTop = " + scrollTop + " widget = "
* + widget.getClass());
* }
* }, 200));
* }
* });
*
*
* @author SCC
*/
public class LastCallBurstEventsMgr {
private static final HashMap MAP = new HashMap();
/**
* The class is model of one 'burst' event that is added to the manager.
*/
public static class BurstEvent {
private final String name_;
private final Function function_;
private final int delayMsec_;
private final Timer timer_;
/**
* Constructor of the 'burst' event.
*
* @param name
* String value with the unique name, which identify the
* event.
*
* @param f
* Function object that will be executed when the timer
* expires.
*
* @param delayMsec
* int value of the timer delay (it's reseted if multiple
* events are added).
*/
public BurstEvent(final String name, final Function f,
final int delayMsec) {
function_ = f;
delayMsec_ = delayMsec;
name_ = name;
timer_ = new Timer() {
@Override
public void run() {
if (function_ != null) {
function_.execute();
}
removeEvent(name_);
}
};
}
}
/**
* Adds an 'burst' event to the manager.
*
* @param e
* Event object that is identified uniquely by its name.
*/
public static void addEvent(final BurstEvent e) {
BurstEvent oe = MAP.remove(e.name_);
if (oe != null) {
// disable the old event.
oe.timer_.cancel();
}
// put the new event and schedule it.
MAP.put(e.name_, e);
e.timer_.schedule(e.delayMsec_);
}
/**
* Removes the event from the manager.
*
* @param eventName
* String value with the name of the event that we need to
* remove.
*/
public static void removeEvent(final String eventName) {
BurstEvent oe = MAP.remove(eventName);
if (oe != null) {
// disable the old event.
oe.timer_.cancel();
}
}
}