Reputation: 37660
I need to make a custom GWT widget from HTML and javascript code. The javascript code should be called on the widget, but the javascript should receive the widget DOM component as a parameter.
Also, the widget's HTML has to be directly dependent on the arguments, given to the widget's constructor.
What is the "idiomatic" way of doing this?
Upvotes: 2
Views: 2141
Reputation: 9900
It is quite simple. You can start by extending Widget
class.
To create DOM representation, you need to use Document.get()
(or other old api depends on what you prefer).
To call external javascript you will need to use JSNI.
Also you will have to override onDetach
and onAttach
methods, so you can notify external JS when your element is added to dom, and when external JS should perform some cleanup (if needed).
Example code:
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());
}
}
Upvotes: 3