Search code examples
vaadinvaadin-flowvaadin23

How to listen to a client-side click event on an element that has no server-side representation in Vaadin?


In my Vaadin application, there are client-side span-elements that do not have a server-side representation through components. These elements are generated by a component from the Vaadin Directory.

For my use case, I need to listen to the user clicking on such a span element, then get a certain data attribute from the element and do something with it in Java server-side.

Is there a way to setup the click listener, add the event data to it and then do something server-side with it using native Vaadin and without creating a fork of the component from the Vaadin Directory?

These span elements have an unique class name, so I can use document.getElementsByClassName to get all of them client-side. I found threads like this that describe how you can add a JavaScript listener to the element, which I could do executing JavaScript from the server changing the client, but how would I react server-side to the event and then do something with it?

In Vaadin you can work with DOMEvents as described here, but don't I need a component server-side whose element I can grab to do this?


Solution

  • It is true that you need to have a server-side counterpart for the element if you want to be able to directly add DOM listeners to it from the server.

    You can use @ClientCallbable (docs) to make it possible to send updates back to the server. The basic idea is that the JavaScript event listener picks out the data attribute value from the clicked span and passes that value as a parameter to the client-side counterpart of the @ClientCallable method on the DOM element that controls the 3rd party component that you're using.

    (I would love to share a useful code example, but that would involve too much guesswork since you haven't shown how the code you have so far is structured.)