(转)Developer's Guide - Event Handlers

[url]https://developers.google.com/web-toolkit/doc/latest/DevGuideUiHandlers[/url]
Events in GWT use the handler model similar to other user interface frameworks. A handler interface defines one or more methods that the widget calls to announce an event. A class wishing to receive events of a particular type implements the associated handler interface and then passes a reference to itself to the widget to subscribe to a set of events. The Button class, for example, publishes click events. The associated handler interface is ClickHandler.

The following example demonstrates how to add a custom ClickHandler subclass to an instance of a Button:

public void anonClickHandlerExample() {
Button b = new Button("Click Me");
b.addClickHandler(new ClickHandler() {
public void onClick(ClickEvent event) {
// handle the click event
}
});
}


Using anonymous inner classes as in the above example can use excessive memory for a large number of widgets, since it results in the creation of many handler objects. Instead of creating separate instances of the ClickHandler object for each widget that needs to be listened to, a single handler can be shared between many widgets. Widgets declare themselves as the source of an event when they invoke a handler method, allowing a single handler to distinguish between multiple event publishers with an event object's getSource() method. This makes better use of memory but requires slightly more code, as shown in the following example:

public class HandlerExample extends Composite implements ClickHandler {
private FlowPanel fp = new FlowPanel();
private Button b1 = new Button("Button 1");
private Button b2 = new Button("Button 2");

public HandlerExample() {
initWidget(fp);
fp.add(b1);
fp.add(b2);
b1.addClickHandler(this);
b2.addClickHandler(this);
}

public void onClick(ClickEvent event) {
// note that in general, events can have sources that are not Widgets.
Widget sender = (Widget) event.getSource();

if (sender == b1) {
// handle b1 being clicked
} else if (sender == b2) {
// handle b2 being clicked
}
}
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值