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:

Element helloButton = ElementFactory.createButton("Say hello");
helloButton.addEventListener("click", e -> {
    Element response = ElementFactory.createDiv("Hello!");
    getElement().appendChild(response);
});
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.

helloButton.addEventListener("click", this::handleClick)
    .addEventData("event.shiftKey")
    .addEventData("element.offsetWidth");

private void handleClick(DomEvent event) {
    JsonObject eventData = event.getEventData();
    boolean shiftKey = eventData.getBoolean("event.shiftKey");
    double width = eventData.getNumber("element.offsetWidth");

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

    Element response = ElementFactory.createDiv(text);
    getElement().appendChild(response);
}

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.