1
votes

I am going to file this as a bug report, but I wanted to check if someone here can see something wrong with what I am doing.

When you expose an instance method from a GWT class through JSNI, this works as expected in JavaScript. Since we are cross compiling Java, I would instead expect this to be bound to the instance automatically. For example:

package com.test;
class Foo {

    public void instanceFunction() {
        this.otherFunction() // will cause an error when called from JSNI!
    }

    public void otherFunction() {
        // does some stuff
    }

    public native JavaScriptObject getInstanceFunction() /*-{
        return [email protected]::instanceFunction();
    }-*/;

}

Currently the workaround is to bind the function yourself (not very portable):

    public native JavaScriptObject getInstanceFunction() /*-{
        return [email protected]::instanceFunction().bind(this);
    }-*/;

This can also be seen as preference, some may prefer that the functions remain unbound. I would say the current functionality is unintuitave and unnecessary. I cannot imagine a use case for having an unbound this directly in Java code. Also, some browsers do not implement bind(1), so my workaround is not robust.

1
And so, what's your question? - Thomas Broyer
I think the functionality of the compiler should be changed. My question is asking if someone knows of a better way, or a reason to keep the compiler how it is. - Chris Malloy
Reason for not changing the compiler: backwards compatibility. Though feel free to ask the enhancement on code.google.com/p/google-web-toolkit/issues/entry, who knows what the compiler guys think… - Thomas Broyer

1 Answers

4
votes

If you want a portable bind, it's as easy as:

var that = this;
return $entry(function() {
   return [email protected]::instanceFunction()();
});