Listening to User Events Using the Element API

The Element API provides the addEventListener method that you can use to listen to any browser event.

Example: Using the addEventListener method to create a click event.

Element helloButton = ElementFactory
        .createButton("Say hello");
helloButton.addEventListener("click", e -> {
    Element response = ElementFactory
  • Clicking the "Say hello" button in the browser sends the event to the server for processing, and a new <div>Hello!</div> element is added to the DOM.

Accessing Data from Events

You can get more information about the element or user interaction by defining the required event data on the DomListenerRegistration returned by the addEventListener method.

Example: Using the addEventData method to define the required event data.

helloButton.addEventListener("click", this::handleClick)

private void handleClick(DomEvent event) {
    JsonObject eventData = event.getEventData();
    boolean shiftKey = eventData
    double width = eventData

    String text = "Shift " + (shiftKey ? "down" : "up");
    text += " on button whose width is " + width + "px";

    Element response = ElementFactory.createDiv(text);
  • The requested event data values are sent as a JSON object from the client.

  • You can retrieve the event data using the event.getEventData() method in the listener.

  • Make sure that you use the:

    • Correct getter based on the data type.

    • Same keys that were provided as parameters in the addEventData method.

The filter and debounce settings in the @DomEvent annotation can also be set through the DomListenerRegistration object. See Using Events with Components for more.