I have one button in Java GWT code. And I have one javascript file in scripts folder. I want to access functions of that js file on Button click.
So how can I call that method from Java GWT code(Button's click event)..?
Can anyone please tell me code or way for accessing js file's function.
Thanks in Advance.
Calling a JavaScript source in Java is pretty simple. If we develop a Java application in which we must use JavaScript, we will create the script file separately, then include and call it in the Java source to run the desired function.
Yes, you can do this in many ways, e.g. plain Java: http://www.javapractices.com/topic/TopicAction.do?Id=42. or using Apache Commons: http://www.kodejava.org/examples/52.html.
The first method is to call the JavaScript function in HTML. For this, you have to create a function then define this function either in the head section or body section of the HTML document. You can either create a link or a button and then an onclick() event is associated with them in order to call this function.
since your code should not depend on the gwt linker (and how it loads code) you need to prefix the call with the right window object. Reapp does not take that into account. So it actually needs to be:
public static native void onMyButtonClick() /*-{
$wnd.myJSfunction();
}-*/;
Create a method like this:
public static native void onMyButtonClick() /*-{
myJSfunction();
}-*/;
Bind your button like this:
myButton.addClickHandler(new ClickHandler() {
@Override
public void onClick(ClickEvent event)
{
onMyButtonClick();
}
});
Done!
Just make sure that the javascript containing your function is loaded before the generated GWT javascript.
Your welcome!
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With