【问题标题】:How to make GWT widget from HTML and javascript?如何从 HTML 和 javascript 制作 GWT 小部件?
【发布时间】:2012-07-28 22:13:22
【问题描述】:

我需要使用 HTML 和 javascript 代码制作自定义 GWT 小部件。应该在小部件上调用 javascript 代码,但 javascript 应该接收小部件 DOM 组件作为参数。

此外,小部件的 HTML 必须直接依赖于提供给小部件构造函数的参数。

这样做的“惯用”方式是什么?

【问题讨论】:

    标签: java gwt


    【解决方案1】:

    这很简单。您可以从扩展Widget 类开始。

    要创建 DOM 表示,您需要使用 Document.get()(或其他旧 api 取决于您的喜好)。 要调用外部 javascript,您需要使用 JSNI

    您还必须重写 onDetachonAttach 方法,以便您可以在将元素添加到 dom 时通知外部 JS,以及何时外部 JS 应该执行一些清理(如果需要)。

    示例代码:

    public class MyWidget extends Widget{
    
         public MyWidget(String params) {
             Document document = Document.get();
             DivElement divElement = document.createDiv();
             divElement.setInnerHtml(params);
             setElement(divElement); //important, widget needs to know it's root element
         }
    
    
         private static native void doJsMagic(Element element)/*-{ //notifies js about element
             $wnd.doSomething(element);
         }-*/;
    
         private static native void undoJsMagic(Element element)/*-{ 
            //notifies js that it should do some cleanup (if needed)
            //since it is unaware of GWT widget lifecycle
            $wnd.undoSomething(element)
    
         }-*/;
    
         @Override
         public void onAttach() {
            super.onAttach();
            doJsMagic(getElement());
         }
    
         @Override
         public void onDetach() {
            super.onDetach();
            undoJsMagic(getElement());
         }
    
    }
    

    【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2010-12-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多