Ravi Nankani
Ravi Nankani

Reputation: 609

gwt calling java function from hand written javascript

This is with reference to this example:

package mypackage;

public MyUtilityClass
{
    public static int computeLoanInterest(int amt, float interestRate,
                                      int term) { ... }
    public static native void exportStaticMethod() /*-{
      $wnd.computeLoanInterest =
      $entry(@mypackage.MyUtilityClass::computeLoanInterest(IFI));
    }-*/;
}

I need to know the javascript code to call this function. If I use <input type="button" onclick=computeLoanInterest(1,2.1,1)/> the example works, but var x = computeLoanInterest(1,2.1,1) does not work. Can someone tell me what am I missing here.

var x = computeLoanInterest(1,2.1,1); makes value of x undefined var x = window.computeLoanInterest(1,2.1,1) shows type mismatch error

Thanks Ravi

Upvotes: 1

Views: 148

Answers (1)

Tomasz Gawel
Tomasz Gawel

Reputation: 8520

The simplest solution is just get rid of $entry wrapper. Just write in your JSNI export method:

public static native void exportStaticMethod() /*-{
    $wnd.computeLoanInterest = @mypackage.MyUtilityClass::computeLoanInterest(IFI);
}-*/;

Why so? The $entry function is defined in com.google.gwt.core.client.impl.Impl where it looks like (I removed the comments):

public static native JavaScriptObject entry(JavaScriptObject jsFunction) /*-{
    return function() {
        try {
            return @com.google.gwt.core.client.impl.Impl::entry0(Ljava/lang/Object;Ljava/lang/Object;Ljava/lang/Object;)(jsFunction, this, arguments);
        } catch (e) {
            throw e;
        }
    };
}-*/;

This is nothing especially suspicious it just wraps your function with some other function but... see the entry0 method signature:

private static Object entry0(Object jsFunction, Object thisObj,
    Object arguments) throws Throwable 

It returns Object - it is probably why you get type mismatch error. And as you see the calling $entry does not add much value :).

Upvotes: 2

Related Questions