Question

I would like to define the GWT JSO property name as a constant in the JSO, in order to avoid typos and benefit from Eclipse code completion, like so:

public final class MyJSO extends JavaScriptObject
{
    /** here is the constant */
    private static final String MY_CONST = "myPropName";

    protected MyJSO() {
        super();
    }

    public native void setMyProp(final boolean pFlag)
    /*-{
        this.@fully.qualified.MyJSO::MY_CONST = pFlag;
    }-*/;

    public native boolean isMyProp()
    /*-{
        if (this.hasOwnProperty(@fully.qualified.MyJSO::MY_CONST)) {
            return this.@fully.qualified.MyJSO::MY_CONST;
        } else {
            return false;
        }
    }-*/;
}

The GWT compiler should be able to replace the String from the constant at compile time, so there is no problem with the object living as Javascript later on.

But this is so totally not working, I'm thinking I may be wrong. :-) Can anyone explain why? Do you have better ideas how to achieve this?

Thanks!

Was it helpful?

Solution

The correct syntax to refer to a static variable is:

@fully.qualified.MyJSO::MY_CONST

No qualifier (this., in your example) is needed since the variable is static.

If you want to set/get a property on the JavaScript object with the constant name do so as follows:

public native void setMyProp(final boolean pFlag) /*-{
    this[@fully.qualified.MyJSO::MY_CONST] = pFlag;
}-*/;

public native boolean isMyProp() /*-{
    if (this[@fully.qualified.MyJSO::MY_CONST] != null) {
        return this[@fully.qualified.MyJSO::MY_CONST];
    } else {
        return false;
    }
}-*/;
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top