tags:

views:

60

answers:

2

How to add an event handler on all div elements with GWT? I tried the following code but the window alerts are not fired up (But "etvoila" class is set up):

  private NodeList<Element> pageDIVElements;
  public void initDiv() {
    MyDIVEventHandler handler = new MyDIVEventHandler();
    pageDIVElements = Document.get().getElementsByTagName("div");
    for (int i = 0; i < pageDIVElements.getLength(); i++) {
      Element elem = pageDIVElements.getItem(i);
      elem.addClassName("etvoila");
      com.google.gwt.user.client.Element castedElem = (com.google.gwt.user.client.Element) elem;
      DOM.setEventListener(castedElem, handler);
    }

class MyDIVEventHandler implements EventListener {
  private Element divElement;
  @Override
  public void onBrowserEvent(Event event) {

    Window.alert("Yeepee");
    if (event.equals(Event.ONMOUSEOVER)) {
      Window.alert("ONMOUSEOVER");
      divElement = Element.as(((NativeEvent) event).getEventTarget());
      divElement.setPropertyString("background-color", "#C6D4E6");
    } else if (event.equals(Event.ONMOUSEOUT)) {
      divElement = Element.as(((NativeEvent) event).getEventTarget());
      divElement.setAttribute("background-color", "");
    }else if (event.equals(Event.ONCLICK)) {
      divElement = Element.as(((NativeEvent) event).getEventTarget());
      divElement.setAttribute("background-color", "");
      Window.alert("ONCLICK");
    }
  }
}

What is wrong in this method?

+1  A: 

Looks like you negelected to sink the events that you want the listener to be notified of. In this case for example I would add the following into initDiv to element or the relevant children.

DOM.sinkEvents(elem, Event.ONCLICK | Event.ONMOUSEOUT | Event.ONMOUSEOVER);
G. Davids
How to use your solution in the code ? I can't make it work.
djondal
Add the following before the line "DOM.setEventListener(castedElem..." : DOM.sinkEvents(castedElem, Event.ONCLICK | Event.ONMOUSEOUT | Event.ONMOUSEOVER);
G. Davids
A: 

Similarly to this question, you can wrap it in a Label.

NodeList<Element> elems = Document.get().getElementsByTagName("div");
for (int i = 0; i < elems.getLength(); i++) {
  Element elem = elems.get(i);
  Label l = Label.wrap(elem);
  l.addClickHandler(new ClickHandler() {
    @Override
    public void onClick(ClickEvent event) {
      Window.alert("yay!");
    }
  });
}
Jason Hall
The code compiles (when correcting get(i) to getItem(i)), but when executing, the following error is thrown java.lang.AssertionError: A widget that has an existing parent widget may not be added to the detach list at com.google.gwt.user.client.ui.Label.wrap(Label.java:79). Is it really possible to wrap this Element into a Label?
djondal