【问题标题】:How to add JavaScript function in Vaadin with return value?如何在 Vaadin 中添加带有返回值的 JavaScript 函数?
【发布时间】:2016-12-06 06:38:21
【问题描述】:

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

是否有可能注册一个有返回值的函数?

【问题讨论】:

    标签: javascript java vaadin vaadin7


    【解决方案1】:

    您可以通过回调另一个 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);
    }
    

    【讨论】:

    • 我使用您的解决方法将内容存储在 JavaScript 变量中,然后我从 HTML 访问该变量。有点棘手,因为在我访问变量时,vaadin 还没有注册它。所以我需要一个超时功能。不是最干净的解决方案,但感谢您的提示。
    【解决方案2】:

    这是 JavaScriptFunction#call(JsonArray) 方法的 JavaDoc,说明不能有返回值:

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

    【讨论】:

    • 我希望有一个解决方法或者其他方法。也许除了JavaScriptFunction之外还有其他API。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-20
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多