Search code examples
javascriptjavavaadinvaadin7

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?


Solution

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