将GWT事件挂钩到外部iframe中的元素上

tri*_*rNZ 11 javascript java gwt dom event-handling

我正在编写一个涉及与iframe中的外部文档交互的GWT应用程序.作为概念证明,我试图将一个点击处理程序附加到一个按钮.

以下适用于javascript

var iframe = document.getElementById("rawJSIFrame");
var doc = iframe.contentDocument;
var body = doc.body;
var button = doc.getElementsByTagName("input").namedItem("submit");
button.onclick = function() {
    alert("Clicked!");
};
Run Code Online (Sandbox Code Playgroud)

试图在GWT中做同等的事情,我做了以下事情:

public void addClickHandlerToSubmitButton(String buttonElementName, ClickHandler clickHandler) {
    IFrameElement iframe = IFrameElement.as(frame.getElement());
    Document frameDocument = getIFrameDocument(iframe);
    if (frameDocument != null) {
        Element buttonElement = finder(frameDocument).tag("input").name(buttonElementName).findOne();
        ElementWrapper wrapper = new ElementWrapper(buttonElement);
        HandlerRegistration handlerRegistration = wrapper.addClickHandler(clickHandler);
    }
}

private native Document getIFrameDocument(IFrameElement iframe)/*-{
        return iframe.contentDocument;
}-*/;
Run Code Online (Sandbox Code Playgroud)

以下是ElementWrapper类:

public class ElementWrapper extends Widget implements HasClickHandlers {

    public ElementWrapper(Element theElement) {
        setElement(theElement);
    }

    public HandlerRegistration addClickHandler(ClickHandler handler) {
        return addDomHandler(handler, ClickEvent.getType());
    }


}
Run Code Online (Sandbox Code Playgroud)

找到按钮的代码工作正常,但不会调用实际的单击事件处理程序.以前有没有人有类似的问题,你是如何解决的?

提前致谢,

小智 10

希尔布兰德对于onAttach()没有调用GWT方法的问题是正确的.

我实现了您的原始解决方案,将以下方法添加到ElementWrapper:

  public void onAttach() {
    super.onAttach();
  }
Run Code Online (Sandbox Code Playgroud)

并且wrapper.onAttach()ElementWrapper创建后调用添加.奇迹般有效!