Xavier
Xavier

Reputation: 9049

How do I pass a function pointer to a javascript function using GWT's JSNI?

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

Upvotes: 4

Views: 2305

Answers (2)

Feller of Trees
Feller of Trees

Reputation: 21

Along the same lines as sinelaw's answer, here's a way to get a callback.

static final native JavaScriptObject createFunction(final Runnable runnable)
/*-{
    return function() {
        [email protected]::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!

Upvotes: 2

sinelaw
sinelaw

Reputation: 16553

You should be able to pass a JavaScriptObject that represents a JavaScript function object. I don't think you can do anything with Java functions, though. 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 didn't try this code but I believe it should work.

Upvotes: 5

Related Questions