Skip to content

Latest commit

 

History

History
40 lines (30 loc) · 1.64 KB

tutorial-event-listener.asciidoc

File metadata and controls

40 lines (30 loc) · 1.64 KB

Using Event Listeners

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 using the third, optional parameter for addEventListener:

helloButton.addEventListener("click", this::handleClick, "event.shiftKey", "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 addEventListener.