Search code examples
javavaadinanchorvaadin14

Vaadin anchor - catch deafult click event


I am new to Vaadin framework and I was wondering if there is a way of catching the deafult click event of an Anchor? (Vaadin14, Java only - v11)

I know i can do this:

Anchor download = new Anchor()
download.getElement().addEventListener("click", event -> doStuff())

but it does not seem to be the deafult built in click listener as i am able to add an anchor with a StreamResource. Then, clicking the Anchor starts the file download - without adding any additional listeners.

Answer to any of these question would solve my problem i believe:

  • Is there a way of catching this anchor click event?
  • Is there a way of triggerring it programatically in the code like the Button click() method?
  • What kind of @DomEvent is this if it is a @DomEvent?

Solution

  • Are you actually using the anchor as a link or as a button? If the latter, you could just use a Button and style it as a link.


    Answer to your questions:

    1. the way you did, addEventListener("click", e ->
    2. download.getElement().callFunction("click") (the same as clickInClient)
    3. I don't think it matters for you. All you need is to react to the event and if you need some data, you can use addEventData()

    You could alternatively try to subclass Anchor implementing the ClickNotifier mixin interface which would provide you with the addClickListener() method, also you could then fire this ClickEvent manually, as is done in button's click()

    public class ClickableAnchor extends Anchor implements ClickNotifier {
        public void click() {
            fireEvent(new ClickEvent<>(this, false, 0, 0, 0, 0, 0, 0, false, false,
                    false, false));
        }
    
        public void clickInClient() {
            getElement().callJsFunction("click");
        }
    }