如何在具有 return 值的 Vaadin 中添加 JavaScript 函数?

How to add JavaScript function in Vaadin with return value?

在 Vaadin 中可以注册一个 JavaScript 函数,例如:

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());
    }
});

是否可以通过某种方式注册具有 return 值的函数?

这是 JavaScriptFunction#call(JsonArray) 方法的 JavaDoc,解释了您不能有 return 值:

     /**
     * 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);

您可以通过回调另一个 JavaScript 方法来解决这个问题。

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 + "');");
    }
});

然后在您的 JS 中调用 openObj 函数时可能如下所示:

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

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