PDA

View Full Version : Simple Event Handler for an HTML element



databass
9 Jun 2009, 8:27 AM
I'm trying to simply add an ONCLICK event-handler to an HTML widget:

Html alertHtml = new Html();
alertHtml.setHtml("Click Me");
alertHtml.addListener(Events.OnClick, new Listener<ComponentEvent>() {

public void handleEvent(ComponentEvent ce) {
com.google.gwt.user.client.Window.alert("I've been clicked");

}
});


This works fine if alertHtml is a button. But as Html, it never runs handleEvent when I click on the Html.

Any idea what I might be missing here?

Thanks,
Dave

Jose Jeria
9 Jun 2009, 12:42 PM
You first need to "sink" the events you want to listen to:


final Html alertHtml = new Html("Click me");

// Can only sink events after that the element has been rendered
final Listener<BaseEvent> attachListener = new Listener<BaseEvent>() {
@Override
public void handleEvent(final BaseEvent be) {
final Html html = (Html) be.getSource();
html.el().addEventsSunk(Event.ONCLICK);
}
};

final Listener<BaseEvent> clickListener = new Listener<BaseEvent>() {
public void handleEvent(final BaseEvent be) {
MessageBox.alert("Alert", "I've been clicked", null);
}
};

alertHtml.addListener(Events.Attach, attachListener);
alertHtml.addListener(Events.OnClick, clickListener);
You can also extend HTML using an inner class to achieve this:


final Html alertHtml = new Html("Click me") {
@Override
protected void onRender(final Element target, final int index) {
super.onRender(target, index);
el().addEventsSunk(Event.ONCLICK);
}
};

alertHtml.addListener(Events.OnClick, new Listener<BaseEvent>() {
public void handleEvent(final BaseEvent be) {
MessageBox.alert("Alert", "I've been clicked", null);
}
});

databass
9 Jun 2009, 1:36 PM
Thanks...I went with the first approach. Worked perfectly.