Disable an Anchor in GWT

Unex­pect­ed­ly, call­ing setEnabled(false) does not pre­vent a link/anchor from being clicked. That means, the click events still get trig­gered.
The rea­son is more or less a bug in GWT as it updates the list of events that are going to be trig­gered only at the moment when it gets attached to the DOM (Btw, in GWT, this process is called to sink and to unsink events, where the for­mer enables a speci­fic event to be trig­gered and the lat­ter dis­ables it).
I found a workaround by cre­at­ing my own Anchor class and forc­ing the under­ly­ing GWT Anchor to update the list of events to be sunk.

...
import com.google.gwt.event.dom.client.ClickHandler;
import com.google.gwt.user.client.Event;

public class Anchor extends com.google.gwt.user.client.ui.Anchor {

	@Override public void setEnabled(boolean enabled) {
		super.setEnabled(enabled);
		if (isAttached()) {
			onDetach();
			if (enabled) {
				sinkEvents(Event.ONCLICK);
			} else {
				unsinkEvents(Event.ONCLICK);
			}
			onAttach();
		}
	}

	@Override protected void onLoad() {
		super.onLoad();
		if (isEnabled()) {
			sinkEvents(Event.ONCLICK);
		} else {
			unsinkEvents(Event.ONCLICK);
		}
	}
}

Note the onLoad method, it sets up the state when the wid­get gets attached to the DOM the first time. It is required because setEnabled() could have been called before the anchor got attached.

If you encoun­tered the same issue, please vote for this bug report.

One Reply to “Disable an Anchor in GWT

Leave a Reply

Your email address will not be published. Required fields are marked *