Search code examples
gwtjsni

Linking to GWT instance method from JSNI does not automatically bind "this"


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.


Solution

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

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