How to use javascript to store variables to window correctly?

45 views
Skip to first unread message

Alex Luya

unread,
Nov 2, 2014, 2:28:12 AM11/2/14
to google-we...@googlegroups.com

I am trying to use JSNI to set/get variable to/from js object:window like this:

private final native <T> T get(String key)/*-{
    return $wnd.key;
}-*/;


private final native void set(String key, Object value)/*-{
    $wnd.key = value;
}-*/;

and if I set a variable: var_1 to window:  (the definition of IdNameImpl is listed in the end)

IdName var_1=IdNameImpl.create("id_1","name_1");
set("key_1",var_1);

then

get("key_1")

I will get var_1 correctly

and then set another variable var_2 to window

IdName var_2=IdNameImpl.create("id_2","name_2"); 
set("key_2",var_2)

then,try to get key_1 again

get("key_1")

unexpectedly,var_2 will be returned

so,the problem is obvious:the get() method will always return the last set variable no matter what key is.Questions are:

1,Why?
2,How to make it right?
Blow is definition of IdNameImpl
public class IdNameImpl extends JavascriptObject implements IdName
{
    public static final IdName create(String Id,String Name)/*-{
        var o=new Object();

        o.Id=Id;
        o.Name=Name;

        return o;
    }-*/;

    protected IdNameImpl()
    {
    }

    @Override
    public final native String getName()/*-{
        return this.Name;
    }-*/;


    @Override
    public final native void setName(String Name)/*-{
        this.Name = Name;
    }-*/;

    @Override
    public final native String getId()/*-{
        return this.Id;
    }-*/;


    @Override
    public final native void setId(String Id)/*-{
        this.Id = Id;
    }-*/;
}

Ignacio Baca Moreno-Torres

unread,
Nov 2, 2014, 5:18:42 AM11/2/14
to google-we...@googlegroups.com
I'm not sure but... "return $wnd.key;" is the same as "return $wnd['key'];" which is not what you want, you should use "return $wnd[key];".

Alex Luya

unread,
Nov 2, 2014, 5:43:03 AM11/2/14
to google-we...@googlegroups.com
Thanks,followed your suggestion,changed to
private final native <T> T get(String key)
/*-{
    return $wnd[key];
}-*/;



private final native void set(String key, Object value)
/*-{
    $wnd[key] = value;
}-*/;
It works now.
--
You received this message because you are subscribed to a topic in the Google Groups "Google Web Toolkit" group.
To unsubscribe from this topic, visit https://groups.google.com/d/topic/google-web-toolkit/_9T201GGrkY/unsubscribe.
To unsubscribe from this group and all its topics, send an email to google-web-tool...@googlegroups.com.
To post to this group, send email to google-we...@googlegroups.com.
Visit this group at http://groups.google.com/group/google-web-toolkit.
For more options, visit https://groups.google.com/d/optout.

Reply all
Reply to author
Forward
0 new messages