Using the GWT ClickListener on an Element
11/24/2008
GWT uses what it calls a ClickListener instead of the standard HTML onclick attribute. The normal way to use a GWT CLickListener would be as follows:
focusWidget.addClickListener(new ClickListener() {
public void onClick(Widget sender) {
// do something here
}
});
Unfortunately, this seems not to work on an HTML Element. Luckily, you can use JSNI to write some native JavaScript and get around the problem:
/**
* Example of adding an onlick attribute to an element.
*/
public native void addClickListener(Element element) /*-{
element.onclick = function() {
// do something here
return false;
};
}-*/;
Just be careful about what your onclick is doing in order to avoid possible memory leaks.
You don’t have to add a click listener. You can just use the DOM.setEventListener(Element elem, EventListener listener) method. Not as messy as JSNI.