How to define and read Global JavaScript Variable in GWT

5,021 views
Skip to first unread message

Ashish Khivesara

unread,
Feb 10, 2010, 2:51:47 PM2/10/10
to google-we...@googlegroups.com
Is there a way to define a global javascript variable in GWT? 
I was able to define one in a sample.js file and then read the same using a JSNI native method. 
But was wondering if there is a way to this purely in Java (GWT) . 

My goal is to be able to have a global object that can be shared between multiple gwt apps which are modules inside the same project.

Thanks
Ashish 

Ashish Khivesara

unread,
Feb 10, 2010, 2:59:10 PM2/10/10
to google-we...@googlegroups.com
In Java we would define static variables to do something like this. Is that the correct approach I can take here as well?

thanks

obesga

unread,
Feb 11, 2010, 8:45:17 AM2/11/10
to Google Web Toolkit
Look at

http://code.google.com/intl/en/webtoolkit/doc/latest/DevGuideCodingBasicsJSNI.html

But, into GWT, you can define a static variable in one class, it'll
work as expected

There are no 'global variables' in Java, but you can do

/*********** Example 1 ***************/
class MyModule{
// Defines a global var in Js accesible by Java code
public static native void setVaar(String value) /*-{
$wnd.vaar = value;
}-*/;

public static native String setVaar() /*-{
return $wnd.vaar;
}-*/;

public void onModuleLoad(){
setVaar("");
}

}
/*********** Example 2 ***************/

class MyModule{

// Defines a static var in Java accesible by Js code
public static native void initJs() /*-{
$wnd.getVaar = function(){
return @com.google.gwt.examples.MyModule::vaar;
};
}-*/;

public static String vaar = "";

public void onModuleLoad(){
initJs()
}

}


On Feb 10, 8:59 pm, Ashish Khivesara <ashish.khives...@gmail.com>
wrote:


> In Java we would define static variables to do something like this. Is that
> the correct approach I can take here as well?
>
> thanks
>
> On Wed, Feb 10, 2010 at 11:51 AM, Ashish Khivesara <
>

Ashish Khivesara

unread,
Feb 11, 2010, 6:02:35 PM2/11/10
to google-we...@googlegroups.com
Great. Thanks a lot for the confirmation and examples.

--
You received this message because you are subscribed to the Google Groups "Google Web Toolkit" group.
To post to this group, send email to google-we...@googlegroups.com.
To unsubscribe from this group, send email to google-web-tool...@googlegroups.com.
For more options, visit this group at http://groups.google.com/group/google-web-toolkit?hl=en.


Reply all
Reply to author
Forward
0 new messages