javascriptjavadom-eventsvaadinlit

Pass data via CustomEvent from JS to Java


I have a Vaadin project

I'm dispatching a CustomEvent from a JS lit component.

I'm listening to it from a Java class and I correctly receive the events emitted.

The following is my JS code:

this.dispatchEvent(new CustomEvent('change', {detail: this.breakLines, bubbles: true, composed: true}));

And the following is my Java listener:

getElement().addEventListener("change", e -> {
    System.out.println("change value: " + e.getEventData());
});

Currently my Java code outputs an empty object {}

How can I extract the data that resides in "detail"?


Solution

  • Vaadin does not submit all properties of the event by default, you need to give it a hint. For example I'm doing this in my recent React example:

        getElement().addEventListener("color-change", e -> {
                    var newValue = e.getEventData().getString("event.hex");
                    setModelValue(newValue, true);
                })
                .addEventData("event.hex")
    

    In your case that could be:

    .addEventData("event.detail")
    

    And then accessing that boolean:

    e.getEventData().getBoolean("event.detail")
    

    Alternatively, you can create a custom event and declare the transferred details with annotations, as described in other answer, but that requires quite a lot more code.