Search code examples
gwtjsni

JSNI - invoking native method from another native method


How to call another native on button click of a native method? can we call more than 1 native method from single native method on button click


Solution

  • Yes you can do it.

    Sample code:

    public void onModuleLoad() {
        exportSayHello();
    
        Button btn = new Button("Click");
        btn.addClickHandler(new ClickHandler() {
    
            @Override
            public void onClick(ClickEvent event) {
                buttonClicked("vartika");
            }
        });
    
        RootPanel.get().add(btn);
    }
    
    public static native void exportSayHello() /*-{
        $wnd.sayHelloFunction = $entry(@com.gwt.test.client.GWTTestProject::sayHello(Ljava/lang/String;));
    }-*/;
    
    public static native void buttonClicked(String value)/*-{
        $wnd.sayHelloFunction(value);
    }-*/;
    
    public static native void sayHello(String value)/*-{
        $wnd.alert("Hello " + value);
    }-*/;
    

    Steps to follow:

    • Export method sayHello() to JavaScript using JSNI
    • Now call it from native method buttonClicked() using the same name sayHelloFunction that is exported to JavaScript.

    Read more about GWT JSNI.