简体   繁体   中英

How to add JavaScript function in Vaadin with return value?

In Vaadin it's possible to register a JavaScript function for example like this:

JavaScript.getCurrent().addFunction("openObj", new JavaScriptFunction() {
    private static final long serialVersionUID = 9167665131183664686L;

    @Override
    public void call(JsonArray arguments) {
        if (arguments.length() != 1) {
            Notification.show("Wrong arguments for openObj: " + arguments.asString());
            return;
        }
        openObject(arguments.get(0).asString());
    }
});

Is it somehow possible to register a function which has a return value?

You could work round this by calling back to another JavaScript method.

JavaScript.getCurrent().addFunction("openObj", new JavaScriptFunction() {
    private static final long serialVersionUID = 9167665131183664686L;

    @Override
    public void call(JsonArray arguments) {
        if (arguments.length() != 1) {
            Notification.show("Wrong arguments for openObj: " + arguments.asString());
            return;
        }
        String val = openObject(arguments.get(0).asString());
        JavaScript.getCurrent().execute("myMethod('" + val + "');");
    }
});

Then in your JS when you call the openObj function could look something like this:

function doStuff(obj){
    openObj(obj);
}

function myMethod(val)
{
    alert(val);
}

This is the JavaDoc for the JavaScriptFunction#call(JsonArray) method, which explains that you cannot have a return value:

     /**
     * Invoked whenever the corresponding JavaScript function is called in the
     * browser.
     * <p>
     * Because of the asynchronous nature of the communication between client
     * and server, no return value can be sent back to the browser.
     * 
     * @param arguments
     *            an array with JSON representations of the arguments with which
     *            the JavaScript function was called.
     */
    public void call(JsonArray arguments);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM