Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Calling Javascript function of .js file from java GWT code

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.

like image 722
Manann Sseth Avatar asked Aug 16 '12 11:08

Manann Sseth


People also ask

Can you call a JavaScript function from Java?

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.

Can we read js file in Java?

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.

How do you call a function in JS file from 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.


2 Answers

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();
}-*/;
like image 96
Daniel Kurka Avatar answered Sep 28 '22 04:09

Daniel Kurka


  1. Import the JS Lib in your .html file.
  2. Create a method like this:

    public static native void onMyButtonClick() /*-{
        myJSfunction();
    }-*/;
    
  3. Bind your button like this:

    myButton.addClickHandler(new ClickHandler() {
    
        @Override
        public void onClick(ClickEvent event)
        {
            onMyButtonClick();
        } 
    
    });
    
  4. Done!

Just make sure that the javascript containing your function is loaded before the generated GWT javascript.

Your welcome!

like image 35
Johan S Avatar answered Sep 28 '22 05:09

Johan S