Vaadin : how to get return value from javascript m

2019-05-31 00:18发布

问题:

I have one JS method showMessage(message)

function showMessage(message) {
 alert(message);
 return "Your message is " + message;
}

I can get arguments of method from my component or UI as

    JavaScript.getCurrent().addFunction("showMessage", new JavaScriptFunction() {

        @Override
        public void call(final JSONArray arguments) throws JSONException {
            System.out.println("Getting call JS method " + arguments);

        }
    });
    Page.getCurrent().getJavaScript().execute("showMessage(Hello World !)");

So , has there anyway to get return values of JS methods in Vaadin ? If yes , how can I figure it out ?

回答1:

no you can't return from there

Because of the asynchronous nature of the communication between client and server, no return value can be sent back to the browser. https://vaadin.com/api/7.2.5/com/vaadin/ui/JavaScriptFunction.html#call(org.json.JSONArray)

To get the return value, you have to actually callback to the server (your defined showMessage method on server side) from your client side showMessage (browser/javascript). I would assume, that your main problem here is naming them both the same (I am not sure, if Vaadin applies here some package name based prefix, but most likely one of your showMessaage methods overrides the other).

You should rename your client's showMessage to something else (requestMessage below) and call your server's showMethod in there.

// client/browser/javascript (remove/rename existing showMessage from your _client_ code)
function requestMessage(m) { showMessage("Requested: "+m) }
// server/vaadin/java
Page.current.javaScript.execute("requestMessage('Hello World')")