Trevor Boyd Smith
Trevor Boyd Smith

Reputation: 19233

Are EventHandlers and SinkEvents doing the same functional job?

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;
         }
     }
 }
  1. Are EventHandlers and SinkEvents doing the same functional job?
  2. If yes, what are the tradeoffs? (where would you use one over the other)
  3. If no, how are they different?

Upvotes: 16

Views: 5063

Answers (1)

Peter Knego
Peter Knego

Reputation: 80330

I'm not GWT expert, but this is what I gather from looking at the GWT source:

  1. All EventHandlers (eventually) call addDomHandler(..) which calls sinkEvents(). 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.

  2. EventHandlers add certain overhead. It's debatable if this matters at all.

  3. 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.

Upvotes: 12

Related Questions