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

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 this.#com.test.Foo::instanceFunction();
}-*/;
}
Currently the workaround is to bind the function yourself (not very portable):
public native JavaScriptObject getInstanceFunction() /*-{
return this.#com.test.Foo::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.

If you want a portable bind, it's as easy as:
var that = this;
return $entry(function() {
return that.#com.test.Foo::instanceFunction()();
});

Related

Javascript module function in GWT with JsInterop

Hoping this is way easier than I'm making it - I'm a Java coder, some inner Javascript aspects are a tad unfamiliar to me.
Trying to embed the great CodeJar library inside a GWT panel. There's a pretty nice/simple example for CodeJar:
<script type="module">
import {CodeJar} from './codejar.js'
import {withLineNumbers} from './linenumbers.js';
const editor = document.querySelector('.editor')
const highlight = editor => {
// highlight.js does not trim old tags,
// let's do it by this hack.
editor.textContent = editor.textContent
hljs.highlightBlock(editor)
}
const jar = CodeJar(editor, withLineNumbers(highlight), {
indentOn: /[(\[{]$/
})
jar.updateCode(localStorage.getItem('code'))
jar.onUpdate(code => {
localStorage.setItem('code', code)
})
</script>
The module function itself looks like this:
export function CodeJar(editor, highlight, opt = {}) { ... }
'editor' is a Div reference, and 'highlight' is a callback library function for handling code highlighting.
What I'm battling with is the JsInterop markup and code to make Javascript modules work with GWT. The above has a few aspects which I'm battling with
replacing the "import" such that the javascript module code is available to GWT. Obvioulsy I can just import the js in my top level index.html, but as I understand it JS modules don't become part of the global namespace, they're only usable from the JS module that imports them. Which in my case, presumably needs to be the GWT code.
how to pass the callback function in when recoding the above in GWT
how to get my own 'jar' reference to do own text set/get (replacing the use of local storage)
To load the script and have it available for GWT consumption, you have (at least) 3 possibilities:
use a static import in a <script type=module>, and then assign the CodeJar function to a window property to make it available globally (that could be another global object than window actually)
use a dynamic import() from GWT, using JsInterop and possibly elemental2-promise
use Rollup/Webpack/whatever to turn the CodeJar module into a non-module script so you can use it differently
Next, you need to create JsInterop bindings so you can call it from GWT; something like that (assuming you made CodeJar available globally as window.CodeJar, and using elemental2-dom for HTMLElement, but com.google.gwt.dom.client.Element would work just as well):
#JsType(isNative = true, namespace = JsPackage.GLOBAL, name = "?")
interface CodeJar {
#JsMethod(namespace = JsPackage.GLOBAL, name = "CodeJar")
static native CodeJar newInstance(HTMLElement element, HighlightFn highlight);
#JsMethod(namespace = JsPackage.GLOBAL, name = "CodeJar")
static native CodeJar newInstance(HTMLElement element, HighlightFn highlight, Options opts);
void updateOptions(Options options);
void updateCode(String code);
void onUpdate(UpdateFn cb);
void destroy();
}
#JsType(isNative = true, namespace = JsPackage.GLOBAL, name = "Object")
class Options {
public String tab;
public JsRegExp indentOn;
public boolean spellcheck;
public boolean addClosing;
}
#JsFunction
#FunctionalInterface
interface HighlightFn {
void highlight(HTMLElement e);
}
#JsFunction
#FunctionalInterface
interface UpdateFn {
void onUpdate(String code);
}
With the above code, you should be able to create an editor using something like:
CodeJar jar = CodeJar.newInstance(editor, MyHighlighter::highlight);
If you use a dynamic import(), replace the static methods with instance ones in a #JsType interface representing the module received from the promise.

Wicket: AjaxRequestTarget vs onModelChanged

I'm working on a code in a wicket project, where the original devs used the onModelChanged() method quite a lot in Ajax request handling methods. I, for one, however am not a strong believer of this implementation.
In fact, I can't think of any examples, where calling the target.add(...) is inferior to calling the onModelChanged method.
Am I missing some key concepts here?
Example:
public MyComponent extends Panel {
public MyComponent(String id, Component... componentsToRefresh) {
add(new AjaxLink<Void>("someId") {
#Override
public void onClick(AjaxRequestTarget target) {
// some logic with model change
for(Component c: componentsToRefresh) {
c.modelChanged();
}
target.add(componentsToRefresh);
}
};
}
}
Now, there are a couple of things I don't agree with, the very first is the componentsToRefresh parameter, the second is (as the question suggests), the fact that we called c.modelChanged() on all components in that array. My guess would be that it is completely un necessary and instead of a parameter in the constructor, one should just write an empty function in MyComponent and override it, and put the necessary components in there when needed.
I would suggest to use Wicket Event system instead. That is, whenever the AjaxLink is clicked you will broadcast an event:
send(getPage(), Broadcast.BREATH, new MyEventPayload(target));
This will broadcast the event to the current Page and all its components.
Then in any of your components you can listen for events:
#Override
public void onEvent(IEvent event) {
Object payload = event.getPayload();
if (payload instanceof MyEventPayload) {
((MyEventPayload) payload).getTarget().add(this); // or any of my sub-components
event.stop(); // optionally you can stop the broadcasting
}
}
This way you do not couple unrelated components in your application.
See Wicket Guide for more information.

In GWT how can we share objects between javascript and java?

I have a pojo in my class containing some methods to manipulate Maps and Arrays in java. This object is used in RPC calls to carry my configurations. I have a mechanism in which before making any RPC call I execute a javascript function. Now what I really want is to pass my configuration object to this javascript function and this javascript function can manipulate this configuration object and finally this manipulated object will be passed in my RPC call.
So how can I pass my java object to javascript and allow manipulating it?
First, you cannot manipulate Java objects from javascript directly. But what you can do, is to export a set of static methods to javascript and use them to manipulate your objects. This is done in this way:
public void onModuleLoad() {
exportHelloMethod(this);
}
public String exportedMethod(String name) {
// Manipulate your java classes here
// return something to JS
}
// Create a reference in the browser to the static java method
private native void exportHelloMethod(HelloClass instance) /*-{
$wnd.hello = instance#[...]HelloClass::exportedMethod(Ljava/lang/String;);
}-*/;
Fortunately there is a library which allows exporting java methods and classes in a simpler way. It is gwt-exporter, and you have just to implement Exportable in your class and use a set of annotations so as the exporter generator does all the work.
#ExportPackage("jsc")
#Export
public class MyClass implements Exportable {
public void show(String s){
}
}
public void onModuleLoad() {
ExporterUtil.exportAll();
}
Then in javascript you can instanciate and manipulate the class:
var myclass = new jsc.MyClass();
myclass.show('whatever');

How to implement a javascript API using JSNI?

I am trying to implement an API (SCORM API) using GWT.
The client code expects an API object with methods like Initialize(), getLastError() and so on...
I tried to implement this api as an Java Object, but i see that the compiled names are changed and cannot be used directly by client code.
I see that gwt-exporter can do the trick (http://code.google.com/p/gwt-exporter/) but i would like to know how to do it using pure gwt and jsni.
As the API is expected as a object, named API_1484_11 attached to the window object, not an function, , i don't see how to use the $entry() idiom.
Here is my current, failing, code:
public final class SCORMApi {
protected SCORMApi() {}
public void Initialize(){
GWT.log("** INITIALIZE CALLED **");
}
public static void create(){
bind(new SCORMApi());
}
public static native void bind(SCORMApi api) /*-{
$wnd.API_1484_11 = api;
}-*/;
}
So, in this context, my question is:
How can i get javascript calls (e.g. window.API_1484_11.Initialize() ) to reach my java gwt code?
You're on the right lines with your bind method. But you haven't understood how to call Java methods from within JSNI. This is how you do it in the case of your Initialize method:
public static native void bind(SCORMApi api) /*-{
$wnd.API_1484_11 = {
initialize: function() {
$entry( api.#com.yourpackage.name.SCORMApi::Initialize()() );
}
};
}-*/;
The blogs Getting To Really Know GWT parts 1 and 2 are required reading on this subject.

GWT JSNI method call failing, but there are no errors

I'm trying to implement Mozilla's Persona in a GWT App. Here's part of the code from a dummy app I set up to test it:
public class OpenId implements EntryPoint {
private native void callWatch(String email)
/*-{
$wnd.navigator.id.watch({
loggedInUser: email,
onlogin: function(assertion){
$wnd.alert("Calling method");
this.#com.gallup.openid.client.OpenId::processLogin(Ljava/lang/String;)(assertion);
$wnd.alert("Called Java Method");
},
onlogout: function(){alert("Logged Out!");}
});
}-*/;
private void processLogin(String assertion){
Window.alert("Logged in!");
personaStatus.setText("Log In Complete.");
}
}
When I call the callWatch method, only the "Calling method" alert box shows up. Neither of the other ones are ever called. So for some reason the code appears to be stopping at the JSNI call right below the first alert. But there are no errors in Dev Mode.
I don't understand why the processLogin method doesn't get called.
I thought I followed Google's Documentation correctly.
I did try writing
this.#com.gallup.openid.client.OpenId::processLogin(Ljava/lang/String;)(assertion);
as OpenID.#... and instance.#... due to this post.
I'm not sure what else to try.
The variable this points to the function that immediately surrounds it, which is in this case your onlogin JavaScript function. You need to use a temporary that variable (a typical JavaScript idiom, by the way)
private native void callWatch(String email)
/*-{
var that = this;
...
onlogin: function(assertion){
that.#com...
And then, ideally use $entry(...), so you will see error messages, if you have registered an UncaughtExceptionHandler.
See also: https://stackoverflow.com/a/5235580/291741