herman
herman

Reputation: 12305

stop event propagation for Vaadin Flow buttons

I have a Vaadin 23 application where I have a Div element with a Button in it (among other content) and a click listener added to it, as well as to the button:

Button button = new Button();
button.addClickListener(event -> { ... });

Div wrapper = new Div(button);
wrapper.addClickListener(event -> { ... });

The problem is that both listeners are firing when the button is clicked.

How can I make sure that only the button click listener is fired in that case? I want the click listener on the Div to fire when I click anywhere inside the Div except on the button.

Alternatively, if I could detect in the click listener on the Div that the click was actually on the button, I could simply ignore it. But I don't see how to do that either.

This is a port from a Vaadin 8 app where it was working correctly. The wrapper Div in that case was a CssLayout with a LayoutClickListener added.

Upvotes: 2

Views: 1039

Answers (1)

Leif Åstrand
Leif Åstrand

Reputation: 8001

There was a highly voted issue for adding this feature to Vaadin Flow. Different workarounds are also described in the issue.

In your case, I think the workaround would look like this:

button.getElement().addEventListener("click", ignore -> {}).addEventData("event.stopPropagation()");

Or from Vaadin 24.2 onwards there exists convenience API to make the workaround easier to find

button.getElement().addEventListener("click", ignore -> {}).stopPropagation();

Upvotes: 3

Related Questions