开发者

GWT adding a ClickHandler to a DOM element

开发者 https://www.devze.com 2023-01-04 15:53 出处:网络
lets say i have a custom widget which has a ClickHandler. Here\'s the example: public class TestWidget extends Composite {

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:

   开发者_StackOverflow 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


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号