GWT 将 ClickHandler 添加到 DOM 元素 [英] GWT adding a ClickHandler to a DOM element

查看:33
本文介绍了GWT 将 ClickHandler 添加到 DOM 元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我有一个带有 ClickHandler 的自定义小部件.示例如下:

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());

我的点击事件没有被触发.我正在努力理解为什么.如果有人可以向我解释这一点或将我链接到我可以阅读的资源,那就太好了.最后,我想知道是否可以在我附加子事件之后添加 clickhandler,以及是否推荐这种方式.提前感谢您的帮助.

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.

咕咕

推荐答案

当你调用 add() 时,Widget.onAttach() 会在被添加到面板中.onAttach 做了一些工作来注册小部件以接收事件.appendChild() 只是将一个 DOM 元素附加到另一个元素上,其他什么都不做.通过这样做,您应该能够让事件在第二种情况下工作:

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);

但是,我没有对此进行测试,我不建议您在实际应用程序中使用它.使用 add() 绝对是首选,这样使用 appendChild() 没有任何好处,可能会导致意外行为.

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.

这篇关于GWT 将 ClickHandler 添加到 DOM 元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆