Adding a click handler for an html element?
I have a page pregenerated for me using html, it looks like a scrollable list of divs, something like:
<html>
<div id="a">
<div>Item A</div>
</div>
<div id="b">
<div>Item B</div>
</div>
</html>
I'd like to grab them in my entry point method, and add a click handler to each. I can't figure out how to do that. I have something like:
public void onModuleLoaded() {
RootPanel rp1 = RootPanel.get("a");
rp1.addClickHandler(...); // can't do this.
}
how can I listen for a click on one of those items in GWT? Is there a way I can just install a global click handler and just 开发者_运维知识库watch for the ID of clicked items and filter on that? I don't necessarily need to add a click handler for each element (and I think the docs recommend against this if you have many elements which require click handlers),
Thanks
Thanks
I haven't tested this, but the general idea is right, and easy enough to extend for more than one target element. You might like to store the elements returned by DOM.getElementById() beforehand to keep things fast. Bear in mind that onPreviewNativeEvent() will be called for every user event, so keep it light.
Event.addNativePreviewHandler(new NativePreviewHandler() {
public void onPreviewNativeEvent(NativePreviewEvent event) {
if (Event.as(event).getTypeInt() == Event.ONCLICK &&
DOM.isOrHasChild(DOM.getElementById("A"), Element.as(event.getEventTarget()))) {
// Element 'A' was clicked.
}
}
}
The problem using wrap() is that if the parent element is already a widget, the wrapping is not allowed. You can still do it and will work, but if you run the application in development mode the assertion will fail, stopping the application.
The right (but tedious and in my opinion incomplete) way is something like
Element elem = DOM.getElementById(“billing-component”);
DOM.sinkEvents(elem, Event.ONCLICK | Event.ONMOUSEOUT | Event.ONMOUSEOVER);
DOM.setEventListener(elem, new EventListener() {
@Override
public void onBrowserEvent(Event event) {
if (Event.ONCLICK == event.getTypeInt()) {
…
}
}
});
I know doesn't look nice, and actually it isn't because you can only attach a single listener to the element and have to check for the event type.
精彩评论