user44697
user44697

Reputation: 323

Adding javascript function to Vaadin

I want to add a javascript function to vaadin so it would be performed when the button is pressed. So far I have tried it these two ways.

String string = "function myFunction(p) {"
    +"alert(p);"
+"}"
JavaScript.getCurrent().execute(string);
JavaScript.getCurrent().execute("myFunction('Hello');");

And

String string = "function myFunction(p1, p2) {"
    +"alert(p);"
+"}"
+"myFunction('Hello');"
JavaScript.getCurrent().execute(string);

Buth both ways ended with no successful result.

Update: I changed the codes so they will print something. Those two codes still doesn't work.

Upvotes: 1

Views: 2006

Answers (1)

kukis
kukis

Reputation: 4634

Your code doesn't work because your myFunction is not registered anywhere when you try to call it. What I mean by this your code:

String string = "function myFunction(p) {"
    +"alert(p);"
+"}"
JavaScript.getCurrent().execute(string);

have no effect. To properly define a function in JavaScript using Vaadin you need to assign it to a some variable. This simple change will enable your code to run:

String string = "soReadyToHelp = function myFunction(p) {"
        +"alert(p);"
    +"}";
JavaScript.getCurrent().execute(string);
JavaScript.getCurrent().execute("soReadyToHelp('Hello');");

Note that, when integrating Vaadin and JavaScript you may find AbstractJavaScriptComponent useful.

Upvotes: 4

Related Questions