问题描述
我正在使用GWT。我开始通过添加EventHandlers来添加事件给我的小部件。
事件处理程序示例代码:
widget.addClickHandler(new ClickHandler(){
@Override
public void onClick(ClickEvent event){
//做某事
}
} );
然后我发现有另一种方法来处理使用sinkEvents()的事件。
沉没事件示例代码(,它调用 sinkEvents()
。 sinkEvents()
是较低级的,它是本地javascript事件处理的浏览器抽象包装。
EventHandlers在sinkEvents的基础上构建,因此它们提供了sinkEvents所具有的所有功能。 它们是不同的:使用EventHandlers,您可以使用不同的事件处理程序注册不同的事件类型,这些事件处理程序可以驻留在不同的类中。事件将被自动路由到适当的处理程序。通过sinkEvents,您可以注册不同的事件类型(通过int,而不是类型安全),但总是调用此小部件的 EventHandlers是一种类型安全的方式来添加和删除事件处理程序,并自动将事件路由到您选择的注册处理程序。如果您使用GWT Widgets,则应使用EventHandlers。 onBrowserEvent(event)
。 EventHandlers会增加一定的开销。这是有争议的,如果这很重要。
I am using GWT. I started adding events to my widgets by adding EventHandlers.
Event handler sample code:
widget.addClickHandler(new ClickHandler() {
@Override
public void onClick(ClickEvent event) {
// do something
}
});
I then found there is another way to handle events using sinkEvents().
Sink events sample code (from this website):
{
...
sinkEvents(Event.ONMOUSEDOWN | Event.ONMOUSEUP | Event.ONMOUSEOVER |Event.ONMOUSEOUT)
...
}
public void onBrowserEvent(Event event) {
Element td = getEventTargetCell(event);
if (td == null) return;
Element tr = DOM.getParent(td);
switch (DOM.eventGetType(event)) {
case Event.ONMOUSEDOWN: {
// do something
break;
}
case Event.ONMOUSEUP: {
// do something
break;
}
case Event.ONMOUSEOVER: {
// do something
break;
}
case Event.ONMOUSEOUT: {
// do something
break;
}
}
}
- Are EventHandlers and SinkEvents doing the same functional job?
- If yes, what are the tradeoffs? (where would you use one over the other)
- If no, how are they different?
I'm not GWT expert, but this is what I gather from looking at the GWT source:
All EventHandlers (eventually) call
addDomHandler(..)
which callssinkEvents()
.sinkEvents()
is lower-level and is a browser-abstraction wrapper around native javascript event handling.EventHandlers are build on top of sinkEvents so they provide all functionality that sinkEvents does.
But usage-wise they are different: with EventHandlers you can register for different event types with different event handlers that can reside in different classes. Events will be automatically routed to appropriate handlers. With sinkEvents you can register for different event types (via an int, not type-safe), but always this widget's
onBrowserEvent(event)
will be called.EventHandlers add certain overhead. It's debatable if this matters at all.
EventHandlers are a type-safe way to add and remove event handlers and an automatic way for events to be routed to the registered handlers of your choice. If you use GWT Widgets than you should use EventHandlers.
这篇关于EventHandlers和SinkEvents是否执行相同的功能性工作?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!