Reputation: 866
I am creating an Anchor as follows:
Anchor a = new Anchor( "Click Me" );
Then I add a click handler:
a.addClickHandler( new ClickHandler() {
@Override
public void onClick(ClickEvent event) {
GWT.log("Anchor Clicked");
}
} );
I want to add the Anchor to a LI element. Since I don't have any Widgets for UL and LI, I use the following construct:
public class ElementPanel extends ComplexPanel {
public ElementPanel(String tagName) {
setElement(DOM.createElement(tagName));
}
@Override
public void add(Widget w) {
add(w, getElement());
}
}
I create my UL element:
ElementPanel ul = new ElementPanel(UListElement.TAG);
I create a LI element:
ElementPanel li = new ElementPanel(LIElement.TAG);
I add my Anchor to LI, then I add LI to UL (after which I add to the document):
li.add(a);
ul.add(li);
This works fine. If instead I change the previous lines as follows, I don't see a log message:
li.getElement().appendChild(a.getElement());
ul.add(li);
Similarly, if instead I try this, I also do not see a message:
li.add(a);
ul.getElement().appendChild(li.getElement());
Previously, I had the UL element in the UIBinder. But since I was not successful in adding a click handler to an Element, I have to resort to the above approach.
Upvotes: 0
Views: 2000
Reputation: 64561
This is how events are handled in GWT: the widget needs to be attached, and that generally means adding it to a container chain up to a RootPanel
. See https://code.google.com/p/google-web-toolkit/wiki/DomEventsAndMemoryLeaks#GWT's_Solution for the details.
The easiest way to have <ul><li>
if your structure doesn't change dynamically is to use an HTMLPanel
(and it's even easier with UiBinder).
If the structure is dynamic, then possibly make a ComplexPanel
whose root element is a UListElement
and which wraps all child widgets into a LIElement
. Have a look at the internals of ComplexPanel
, you'll see that it attaches and detaches the child widgets whenever they are added/removed while the panel itself is attached, or whenever the panel is attached / detached.
Upvotes: 1