Search code examples
javajavascripthtmlgwtjsni

How to use JavaScript callback function in GWT UiBinder?


I want to do Facebook Login on a mobile web page. This can be done with a Facebook Login Button. It works great. I have the following code in my GWT UiBinder page:

<g:HTMLPanel>
    <div class="fb-login-button" data-max-rows="1" data-size="xlarge" 
                data-show-faces="false" data-auto-logout-link="false" 
                data-scope="email,publish_actions,user_birthday,user_likes" 
                onlogin="alert('I am a JavaScript callback');"></div>

</g:HTMLPanel>

If login is successful, the onlogin JavaScript function is called.

How can I use this callback function somehow to get notified when this function is called? Is there a way to use JSNI or something else here?


Solution

  • Here is the correct working version based on logans answer. I added the instance variable which is needed because the myOnload() method is non-static. I also added the $entry() function to track error in GWT.

    class MyClass{
    
       MyClass(){
    
         expose();
    
         // UiBinder stuff here
       }
    
       // Call this once. Exports your Java method as a javascript method
       public native void expose()/*-{
           var instance = this;
           $wnd.myOnLoadThing = $entry(function(){
               [email protected]::myOnload()();
           });
        }-*/;
    
       public void myOnload(){
           // Put your java onload function here
       };
    }
    

    And in your uiBinder, make sure to call that myOnLoadThing

    <g:HTMLPanel>
    <div class="fb-login-button" data-max-rows="1" data-size="xlarge" 
                data-show-faces="false" data-auto-logout-link="false" 
                data-scope="email,publish_actions,user_birthday,user_likes" 
                onlogin="window.myOnLoadThing();"></div>
    
    </g:HTMLPanel>
    

    There's also a good answer here: How to call GWT java function from Javascript?