0

I struggle to catch events after famous DOM.appendChild. After many attempts of use handlers I found this answer where @Õzbek did the job via listener. And now I don't get it why "listener" works while "handler" not. As an example in code:

Button button = new Button("Test button");

DOM.appendChild(getElement(), button.getElement());
button.addClickHandler(new ClickHandler() {

    @Override
    public void onClick(ClickEvent event) {
        GWT.log("this doesn't work");        
    }
});

DOM.sinkEvents(button.getElement(), Event.ONCLICK);
DOM.setEventListener(button.getElement(), new EventListener() {
    public void onBrowserEvent(Event event) {
        GWT.log("this works perfectly!");
    }
});

the listener will be working but handler not.

  1. So where is difference beetwen them?
  2. And how to force handler to work?
  3. Is there are some way to do this on handlers ?

I'm trying to understand the difference between listeners and handlers. I read these answers which shows that there is no big difference but I still don't get it

Community
  • 1
  • 1
Dawid D
  • 1,057
  • 13
  • 28

2 Answers2

2

Button is a Widget not an element, and if you add it as an element to the dom you would lose the events. You can either append it to the RootPanel: RootPanel.get().add(button) if you want to use the handler.

if you want to use the element not the widget you can use DOM.createButton(), and use the listener.

zakaria amine
  • 3,412
  • 2
  • 20
  • 35
2

setEventListener of widgets is only called when they are "attached" (to a parent widget, which is itself attached, or delayed until it is attached), and you never "attach" the button.

With an explicit serEventListener you completely bypass the widget internals (and lifecycle). You could actually just use a ButtonElement in this case.

TL;DR: don't do that, it's a symptom of a broken design.

Thomas Broyer
  • 64,353
  • 7
  • 91
  • 164
  • But in some cases you do not have other option for instance if you would like to extend TextBox and add inside a button for showing some helper, the listener is only one option, am I right ? – Dawid D Mar 13 '17 at 08:51
  • 1
    You don't "extends a textbox and add a button", you compose a textbox and a button inside a composite widget. – Thomas Broyer Mar 13 '17 at 19:25