Exposing GWT

While working with GWT, I came across a situation where I needed to interact with a GWT based component from some Javascript function that is outside of GWT. GWT components are written in Java and compiled into Javascript with possibly obfuscated identifiers. How does one do that?

The solution is to expose the GWT object through Javascript Native Interface (JSNI) that can correctly locate classes and methods before the Google compiler mangles the names. GWT’s documentation on writing JSNI

Example

Suppose that I want to trigger a custom event on a GWT (in this case, an EXT-GWT) object from my javascript. Let’s look at what that JSNI involves.

private native void exposeButtonSelect(Button button) /*-{
	$wnd.myButtonSelect = function() {
	button.@com.extjs.gxt.ui.client.widget.Component::fireEvent(Lcom/extjs/gxt/ui/client/event/EventType;)(@com.extjs.gxt.ui.client.event.Events::Select);
	};
}-*/;

Explanation

  • $wnd is a special GWT variable used to correctly reference the window object from within JSNI.
  • Notice that “button” is referring to the button object that you are working with from within Java.
  • @com.extjs.gxt.ui.client.widget.Component::fireEvent is the fireEvent() method being called on the “button” object which is defined in the Component class.
  • (Lcom/extjs/gxt/ui/client/event/EventType;) is identifying the parameter type of the method signature.
  • (@com.extjs.gxt.ui.client.event.Events::Select) is the actual argument object being passed to the method.
  • So now I can call myButtonSelect() from any other javascript, even from other frameworks or listener callbacks.
...
xhr.onreadystatechange = myButtonSelect;
...

It's only fair to share...
Share on FacebookGoogle+Tweet about this on TwitterShare on LinkedIn

Leave a Reply