ClickHandler on an existing element in GWT
I have an HTML document. In that document, there is an element (like button, div, a) with an ID. I know I can use:
Document.get().getElementById("id");
to find the required element in the HTML file. How can I add a Click h开发者_开发技巧andler to it? ClickHandlers only seem to be available on the Button class.
Thanks
If you're trying to add a ClickHandler
to a <button>
, you can do that with Button.wrap()
.
For an <a>
yo can use Anchor.wrap()
(Anchor
s only have ClickListener
s, not ClickHandler
s...yet)
For a <div>
you can use Label.wrap()
(Label
s are just <div>
s).
Suggestion : Try learning how to use UiBinder (added in GWT 2.0).
In your case, you could have done :
yourView.ui.xml
...
<g:Button ui:field="btnName" />
...
yourView.java
public class yourView extends Composite {
interface MyUiBinder extends UiBinder<LayoutPanel, yourView> {}
private static MyUiBinder uiBinder = GWT.create(MyUiBinder.class);
@UiField Button btnName;
public yourView() {
initWidget(uiBinder.createAndBindUi(this));
}
@UiHandler("btnName")
void handleClick(ClickEvent e) {
//Do whatever
}
}
With "@UiHandler" you can add any handler the widget can support (implement Has****Handler). Adding other element to that structure is easy and FAST and you can add any kind of handler to it. @UiField create a variable containing the instance of the element that is manipulatable anywhere in your class.
One other suggestion - use GQuery. It makes it easy to attach a simple event listener to the DOM without creating the extra elements that GWT widgets often do:
$("id").click(new Function() {
public boolean f(Event e) {
Window.alert("This is GWT code without widget baggage!");
return true;
}
});
See here for more: http://code.google.com/p/gwtquery/wiki/GettingStarted#Add_an_event_handler
It is a shame there is not more progressive enhancement based GWT code. IMHO, CSS/HTML do a great job at design/markup - it is just the Javascript I want to replace.
Just do it by setting an event listener.
Event.sinkEvents(e, Event.ONCLICK);
Event.setEventListener(e, new EventListener() {
@Override
public void onBrowserEvent(Event event) {
Window.alert("Clicked!");
}
});
精彩评论