2016-12-06 34 views
1

在Vaadin有可能注册一个JavaScript函数,例如像这样:如何使用返回值在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()); 
    } 
}); 

是它在某种程度上可以注册具有返回值的函数?

回答

3

你可以工作,这一轮的回调到另一个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); 
} 
+0

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

0

这是JavaScriptFunction#调用(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); 
+0

我希望的解决方法,或者一些其他的办法。也许除了'JavaScriptFunction'之外还有其他的API。 –

相关问题