Monday, August 17, 2015

GWT Application calling JS Function written in External JS File

GWT Application calling JS Function written in External JS File
Lets create our own simple Js file named as MyJSTest.js
function count_siddhu() {
    for(var i=1; i<=3; i++) {
        alert("siddhu count "+i)
    }
}
      
In our *.html file add this line of code

<script type="text/javascript" language="javascript" src="MyJSTest.js"></script>

In our client side use this code

      
       public static native void onMyButtonClick() /*-{
     $wnd.count_siddhu();
       }-*/;
      
      
       /**
        * This is the entry point method.
        */
       public void onModuleLoad() {
              //onMyButtonClick();
              final Button sendButton = new Button("Send");         

              // We can add style names to widgets
              sendButton.addStyleName("sendButton");
             
              RootPanel.get("sendButtonContainer").add(sendButton);
             
              // Create a handler for the sendButton and nameField
              class MyHandler implements ClickHandler, KeyUpHandler {
                     /**
                      * Fired when the user clicks on the sendButton.
                      */
                     public void onClick(ClickEvent event) {
                           //sendNameToServer();
                            onMyButtonClick();
                     }

                     /**
                      * Fired when the user types in the nameField.
                      */
                     public void onKeyUp(KeyUpEvent event) {
                           if (event.getNativeKeyCode() == KeyCodes.KEY_ENTER) {
                                  onMyButtonClick();
                           }
                     }

             
              }

              // Add a handler to send the name to the server
              MyHandler handler = new MyHandler();
              sendButton.addClickHandler(handler);
             
       }

In short

1-  Import the JS Lib in your .html file.
2-  Create a method like this:
public static native void onMyButtonClick() /*-{
     $wnd.count_siddhu();
       }-*/;

3-  Bind your button like this:
public void onClick(ClickEvent event) {
                           //sendNameToServer();
                            onMyButtonClick();
                     }

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




No comments: