Listening to User Events

To make an application interactive, you want to react to events from the user. For this, you can listen to any browser event using addEventListener in Element:

Java

  1. Element helloButton = ElementFactory.createButton("Say hello");
  2. helloButton.addEventListener("click", e -> {
  3. Element response = ElementFactory.createDiv("Hello!");
  4. getElement().appendChild(response);
  5. });
  6. getElement().appendChild(helloButton);

Clicking the “Say hello” button in the browser will now send the event to the server, where it is processed and a new “Hello!” element is added to the DOM.

Accessing Data From the Event

Sometimes you need more information about the element or the event which the user interacted with. You can get this by defining required event data on the DomListenerRegistration returned by addEventListener.

Java

  1. helloButton.addEventListener("click", this::handleClick)
  2. .addEventData("event.shiftKey")
  3. .addEventData("element.offsetWidth");
  4. private void handleClick(DomEvent event) {
  5. JsonObject eventData = event.getEventData();
  6. boolean shiftKey = eventData.getBoolean("event.shiftKey");
  7. double width = eventData.getNumber("element.offsetWidth");
  8. String text = "Shift " + (shiftKey ? "down" : "up");
  9. text += " on button whose width is " + width + "px";
  10. Element response = ElementFactory.createDiv(text);
  11. getElement().appendChild(response);
  12. }

The requested event data values are sent as a JSON object from the client and made available through event.getEventData() in the listener. You should use the proper getter based on the data type. Also make sure you use the same keys that you provided as parameters to addEventData.

Tip
The filter and debounce settings in @DomEvent that are described in Using Events with Components can also be set through the DomListenerRegistration object.