2016-12-06 1 views
1

En Vaadin il est possible d'enregistrer une fonction JavaScript par exemple comme ceci:Comment ajouter une fonction JavaScript dans Vaadin avec une valeur de retour?

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

Est-il possible d'enregistrer en quelque sorte une fonction qui a une valeur de retour?

Répondre

3

Vous pouvez travailler autour de ce en appelant de nouveau à une autre méthode 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 + "');"); 
    } 
}); 

Puis dans votre JS lorsque vous appelez la fonction openObj pourrait ressembler à ceci:

function doStuff(obj){ 
    openObj(obj); 
} 

function myMethod(val) 
{ 
    alert(val); 
} 
+0

J'ai utilisé votre solution de contournement pour stocker le contenu dans une variable JavaScript, à laquelle j'accède ensuite à partir du code HTML. Était un peu difficile car au moment où j'accède à la variable, vaadin ne l'a pas enregistré. J'avais donc besoin d'une fonction de temporisation. Pas la solution la plus propre, mais cela fonctionne grâce à l'indice. –

0

C'est le JavaDoc pour la méthode appel JavaScriptFunction de # (JsonArray), ce qui explique que vous ne pouvez pas avoir une valeur de retour:

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

J'espérais une solution de contournement ou peut-être une autre approche. Peut-être qu'il y a une autre API que JavaScriptFunction. –