Finding out when a GWT module has loaded
Asked Answered
S

1

5

I am exporting a GWT method to native javascript in the following manner:

public class FaceBookGalleryEntryPoint implements EntryPoint {

    @Override
    public void onModuleLoad() {

        FacebookGallery facebookGallery = new FacebookGallery();
        RootPanel.get().add(facebookGallery);

        initLoadGallery(facebookGallery);
    }

    private native void initLoadGallery(FacebookGallery pl) /*-{
        $wnd.loadGallery = function (galleryId) {
            [email protected]::loadGallery(Ljava/lang/String;)(galleryId);
        };
    }-*/;
}

In the host page, I am trying to invoke it:

<html>
    <head>
        <title>Facebook image gallery</title>
        <script type="text/javascript"
            src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"></script>     
    </head>

    <body>
        <script type="text/javascript" src="/fbg/fbg.nocache.js"></script>
        <h1>Facebook gallery test</h1>
        <script type="text/javascript">
            $(document).ready(function() {
                loadGallery('blargh');              
            });
        </script>
    </body>
</html>

Unfortunately, when the document.ready callback is invoked, the function is not yet defined. When manually executed from the Firebug console the function works just fine.

I could perform some polling every 50 milliseconds until I find a defined function by that name, but it seems like a horrible approach.

How can I get notified when the module is loaded and therefore when the function is available?

Safari answered 17/11, 2010 at 23:59 Comment(0)
P
14

I would try to define a callback function in the hostpage and call it from GWT at the end of the onModuleLoad() method.

Hostpage function:

<script type="text/javascript">
  function onGwtReady() {
    loadGallery('blargh');              
  };
</script>

GWT:

public void onModuleLoad() {
  FacebookGallery facebookGallery = new FacebookGallery();
  RootPanel.get().add(facebookGallery);

  initLoadGallery(facebookGallery);

  // Using a deferred command ensures that notifyHostpage() is called after
  // GWT initialisation is finished.
  Scheduler.get().scheduleDeferred(new Command() {
    public void execute() {
      notifyHostpage();
    }
  }
}

private native void notifyHostpage() /*-{
  $wnd.onGwtReady();
}-*/;
Prosody answered 18/11, 2010 at 0:23 Comment(3)
Thanks, looks interesting - especially the DeferredCommand bit. I'll give this a shot tonight.Safari
BTW, with GWT 2.1 you should be using Scheduler().get().scheduleDeferred()Safari
Thanks for the Scheduler hint.Prosody

© 2022 - 2024 — McMap. All rights reserved.