2016-12-06 32 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。 –

相關問題