Invoking Java methods from JavaScript: Help!

0 views
Skip to first unread message

luttkens

unread,
Apr 24, 2008, 2:35:37 AM4/24/08
to Google Web Toolkit
I've read an article about how to invoke Java methods from JavaScript.
As I understand it, it's about how you can define a funtction in the
GWT-app like this

static void staticFoo(String s) {
Window.alert("Hello world!");
}

... and call it from JavaScript-code inside a HTML-webpage, like this:

<INPUT TYPE="submit" class="gwt-Button" value="Save"
onClick="@com.google.gwt.examples.JSNIExample::staticFoo(Ljava/lang/
String;)(s);">

But the article isn't clear about where I shold put the code, or maybe
it is just me...

Adam T

unread,
Apr 24, 2008, 6:57:53 AM4/24/08
to Google Web Toolkit
Hi,

You example won't, unfortunately work - since the GWT compiler will
obfuscate your method name - but it's easy to work around that. Just
write a method that "places" your method name into the web page, e.g.

public native void setUp()/*-{
$wnd.staticFooInPage = function(a){
@com.google.gwt.examples.JSNIExample::staticFoo(Ljava/lang/
String;)(s);;
}
}-*/;

Now staticFooInPage is visible to your HTML. Your original method
staticFoo is just a simple Java method

public static void staticFoo(String s){
Window.alert(s);
}

then you can write you HTML sort of how you suggest but reference the
staticFooInPage JavaScript method instead, i.e.

<INPUT TYPE="submit" class="gwt-Button" value="Save"
onClick="staticFooInPage("Some String you want");">

Hope that helps!
//Adam

luttkens

unread,
Apr 24, 2008, 1:20:33 PM4/24/08
to Google Web Toolkit
Hi, thanks for your reply...but:

It doesn't work...

I copied your code but replaced "com.google.gwt.examples.JSNIExample"
with "se.luttkens.client.Songbok" where "se.luttkens.client" is my
root (my path is src/se/luttkens/client). Songbook is the name of the
java-file (and the class name as well).

I placed the first two codes before onModuleLoad function, that is the
Entry Point Method.

Did I do something wrong. Everything complies...but know messages is
shown..

//Magnus
> > it is just me...- Dölj citerad text -
>
> - Visa citerad text -

Adam T

unread,
Apr 24, 2008, 2:15:15 PM4/24/08
to Google Web Toolkit
Hej Magnus,

You did call the setUp() method from somewhere within your
onModuleLoad() method?

MvH

//Adam
Reply all
Reply to author
Forward
0 new messages