What exactly is BrowserEvent and NativeEvent for GWT?

events, gwt

Solution

GWT has a concept of sunk events. All sunk events, but only those, are passed to a `EventListener`'s `onBrowserEvent`.

At the lowest level, you attach an `EventListener` to an `Element` using `DOM.setEventListener` and sink events with `DOM.sinkEvents` (or more recently `DOM.setBitlessEvents`). To avoid memory leaks (particularly –if not only– in old IEs), you have to make sure you set an `Element`'s `EventListener` to `null` before the page unloads.

A `Widget` is an `EventListener` and handles a few of these things for you: it automatically calls `DOM.setEventListener` in its `onAttach` and `onDetach`, and it keeps track of sunk events: its `sinkEvents` is additive to make it easier to work with, and therefore has an `unsinkEvents` counterpart.

Later on, in GWT 1.6, event handlers have been added, and `addDomHandler` (and more recently `addBitlessDomHandler`) automatically calls `sinkEvents` with the appropriate values (taken from the `DomEvent.Type` passed as argument); and to make all of this work, the default behavior of `onBrowserEvent` in widgets is to dispatch events to the registered handlers.

The reason for these bitless variants is that events were originally referred to as `int` constants in a bitfield, but browsers have more and more events so GWT started to run out of bits. The bitless variants are only usable for browsers that do not leak, as widgets don't keep track of which events have been registered that way to unregister them from their `onDetach`, contrary to bit-based events.

All these new `DomEvent`s (with their handlers) starting with GWT 1.6 are wrappers around a `NativeEvent`. There are two kinds of `GwtEvent`s: native ones (`DomEvent`s), which are dispatched by the browser, and logical ones which are dispatched by GWT itself and are not mapped to events at the DOM level. `addDomHandler` is only concerned about `DomEvent`s, aka native events.

Wrapping up: when you exit a text field that you just modified, the browser dispatches a `change` event. If the `TextBox` widget has sunk that event, its `onBrowserEvent` will be called with an `Event` (which is just a legacy subclass of `NativeEvent`) representing that event. The default implementation of `onBrowserEvent` then creates a `ChangeEvent` and dispatches it to the registered `ChangeHandler`s.

Problem

What exactly is browser event? For example if I have a custom widget which contains a single button which overrides onBrowserEvent. And onBrowserEvent method is only called when you click on the button. I thought this event is called for all the events such as onMouseOver, onMouseOut, KeyPressed etc... Also when you're adding DomHandler to make a widget listen to an event which is not supported by as a default. In the docs it says "Adds a native event handler to the widget and sinks the corresponding native event" What do you mean by native event in this context? Thanks

Original source