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
.createDiv("Hello!");
getElement().appendChild(response);
});
getElement().appendChild(helloButton);
-
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)
.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.
-
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.
-
Tip
|
The filter and debounce settings in the @DomEvent annotation can also be set through the DomListenerRegistration object. See Using Events with Components for more.
|
1987D45F-B84D-43AD-A64A-CBEE3FA15FBD