Pre-editing: I wrote this answer, not trying to understand why you tried to do this, assuming you were using some kind of non-browser event that is already pretty well wrapped, and if you want to get more data from the NativeEvent
instance, you can write JSNI methods in your own classes to access it, or another subclass of NativeEvent
to add additional methods and .cast()
to your class. Add a handler to the widget using the Widget.addDomHandler
method and the corresponding MouseEvent
subclass to get an instance of the type.
In JavaScript, callbacks are simply functions that will be called when something happens. Unless specifically indicated where they are being transferred, they are usually called in a global context, and not on a specific instance of the object.
var callback = function() { alert("callback called!"); };
To call a function in an instance (i.e. make it a method call), you can wrap this call in a function that does not need an instance:
var obj = {}; obj.name = "Me"; obj.whenSomethingHappens = function() { alert("my name is " + this.name); };
In Java, you cannot refer specifically to a method (without reflection), but only to instances of objects. The easiest way to create a simple callback is to implement an interface, and the code that receives the callback takes an instance of the interface and calls a specific method.
GWT declares a Command
interface for functions with a null argument and a common Callback<T,F>
interface for cases that may or may not be executed, with one common argument for each parameter. Most event handlers in GWT simply define a single method with the specific data passed to that method.
We must use all this knowledge to transfer Java instances using the call function in JavaScript and make sure that they are called on the right instance. This example is a function that accepts a Callback
instance, and using JSNI terminates the JS call.
// a callback that has a string for either success or failure public native void addCallback(Callback<String, String> callback) /*-{ var callbackFunc = function() { // obviously the params could come from the function params callback.@com.google.gwt.core.client.Callback ::onSuccess(Ljava/lang/String;)("success!"); }; doSomethingWith(callbackFunc);//something that takes (and presumably calls) the callback }-*/;
One last part - for correct error handling and GWT planning to work correctly, it is important to transfer the call back to java in $ entry - the last line should be
doSomething($entry(callbackFunc));