So, I know that in GWT I can write JSNI code that is purely javascript code. But, unfortunately JSNI code does not compile if I use ES6 code within it.
That means that, for example, I cannot do stuff like this:
private native void jsniMethod(String jsModule) /*-{
import(jsModule)
.then(loadedModule => {
doStuffWithLoadedModule(loadedModule);
})
.catch(err => alert(err));
}-*/;
Is there a way to achieve this in GWT code? I mean, I need a reference to a loadedModule so I can use it in some jsni code (the doStuffWithLoadedModule method implementation).
Thanks!
This cannot be done. You need to put JS features that are not supported from JSNI into some kind of external JS, or rewrite them in older JS which is compatible with JSNI. Consider ScriptInjector as one option for this, or your host html page.
For this specific thing, you just need to replace the arrow operator with a function:
private native void jsniMethod(String jsModule) /*-{
import(jsModule)
.then(function(loadedModule) {
doStuffWithLoadedModule(loadedModule);
})
.catch(function(err) { alert(err) });
}-*/;
As an alternative, to use java lambdas, you can use JsInterop. Keep in mind that import
isn't actually a function call, but a js keyword, though this should still work:
@JsMethod(namespace = "<window>")
public native Promise<Object> import(String jsModuleName);
Then, you can invoke this and pass in Java lambdas:
private void notJsniMethod(String jsModule) {
import(jsModule)
.then(loadedModule -> {
doStuffWithLoadedModule(loadedModule);
return null;
})
.catch_(err -> {
DomGlobal.alert(err.toString())
return null;
});
}
Changes from the original JS/JSNI:
=>
is replaced with java's ->
, which operates nearly the same wayalert(...)
is now DomGlobal.alert(...)
, since java doesn't have a "global" namespacereturn null
is required, since java doesn't let you just "forget" to return a value when a value is required..catch(...)
is replaced with .catch_(...)
, since Java doesn't permit a keyword to be used as an identifier