Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

GWT adding a ClickHandler to a DOM element

Tags:

gwt

lets say i have a custom widget which has a ClickHandler. Here's the example:

public class TestWidget extends Composite {

private static TestWidgetUiBinder uiBinder = GWT
        .create(TestWidgetUiBinder.class);

interface TestWidgetUiBinder extends UiBinder<Widget, TestWidget> {
}

@UiField
Button button;

public TestWidget(String firstName) {
    initWidget(uiBinder.createAndBindUi(this));
    button.setText(firstName);
}

@UiHandler("button")
void onClick(ClickEvent e) {
    Window.alert("Hello!");
}

}

When i try to add this Widget like this:

    TestWidget testWidget = new TestWidget("myTestWidget");
    RootPanel.get().add(testWidget);

everything is fine. If i click on my button i get the message i expect. However if i add it like this:

TestWidget testWidget = new TestWidget("myTestWidget");
    RootPanel.getBodyElement().appendChild(testWidget.getElement());

my click event is not being fired. I'm struggeling to understand why. It would be nice if someone could explain this to me or link me to an resource where i can read this up. Finally i would like to know if it is possible to add the clickhandler afterwards i appended the child event and if that way is recommended. Thanks it advance for help.

kuku

like image 800
kukudas Avatar asked Jun 20 '10 22:06

kukudas


1 Answers

When you call add(), Widget.onAttach() is called on the widget that is being added to the panel. onAttach does some work to register the widget to receive events. appendChild() simply attaches one DOM element to another and does nothing else. You should be able to get events working in the second case by doing this:

Element element = testWidget.getElement();
RootPanel.getBodyElement().appendChild(element);
DOM.sinkEvents(element,
    Event.getTypeInt(ClickEvent.getType().getName())
    | DOM.getEventsSunk(element);

However, I haven't tested this and I wouldn't recommend that you use it in a real application. Using add() is definitely preferred, using appendChild() in this way has no advantages and may lead to unexpected behaviour.

like image 168
dslh Avatar answered Oct 18 '22 08:10

dslh