How to pass a pointer to javascript function using GWT JSNI?

I used JSNI before, but I never had to pass a function pointer as a parameter using it, and I'm not sure how to do it. Any help is appreciated!

+3
source share
2 answers

You should be able to pass a JavaScriptObject that represents the object to a JavaScript function. However, I do not think that you can do anything with Java functions. So, for example, you could:

final native JavaScriptObjet myFuncCreator() /*-{
    return function (x, y) { return y - x; };
}-*/

final native int myFuncUser(JavaScriptObject funcObj, int a, int b) /*-{
    return funcObj(a,b);
}-*/

Admittedly, I have not tried this code, but I believe that it should work.

+5
source

On the same lines as with sinelaw, here is a way to get a callback.

static final native JavaScriptObject createFunction(final Runnable runnable)
/*-{
    return function() {
        runnable.@java.lang.Runnable::run()();
    }
}-*/

static final void registerOnClickCallback(Element element, final Runnable runnable) {
    JavaScriptObject callback = createFunction(runnable);
    _registerOnClickCallback(element, callback);
}

static final native void _registerOnClickCallback(Element element, JavaScriptObject callback)
/*-{
    element.onclick = callback;
}-*/

Hope this helps!

+2

Source: https://habr.com/ru/post/1788863/


All Articles