jquerygwtevent-handlingjquery-eventsgwtquery

GWT listen to external custom Javascript event


I'm working on a GWT application and I would like to make that app listen for external custom Javascript events. Those events would be triggered from outside my module.

Basically, just like what you would do in a basic web app with some jQuery :

$('#foo').bind('customEvent', function() {
    ...
});
...
$('#foo').trigger('customEvent');

I tried to achieve this with GWTQuery by overriding the onAttach method in my Composite:

@Override
protected void onAttach() {
    super.onAttach();
    $("#mainView").bind("refreshSheet", new Function() {
        public boolean f(Event e) {
            refreshSheet();
            return true;
        }
    });
}

This is not working, the callback function is being called while I haven't triggered the event on the other side.

What would you suggest to achieve this goal ?


Solution

  • I had the same problem. In the solution below, I send the event from JS by calling a Java method (from my Javascript code) who generates a GWT event. So here is my suggestion:

    in JS:

    window.parent.sendEvent(evendID, eventBody)
    

    (I had to call the window.parent as the GWT and the JS were in 2 separate frames)

    but before I registred the method in GWT (see below) as explained in https://developers.google.com/web-toolkit/doc/latest/DevGuideCodingBasicsJSNI#calling

    in GWT:

    package com.mypackage.client;
    class myclass {
    public static int generateEvent(int eventID, String eventBody) { ...... }
    
    public static native void exportStaticMethod() /*-{
    $wnd.sendEvent=
         $entry(@com.mypackage.client.myclass::generateEvent(ILjava/lang/String;));
    }-*/;
    }
    

    where I is evendID (Integer in JNI) and Ljava/lang/String; is the eventBody string. You have to call this method exportStaticMethod() from your onModuleLoad() method.

    the generateEvent() method from myclass then generates a GWT custom event (as explain in the link from Abhijith). So I don't broadcast an event from JS to GWT through the JS stack this way, but I keep a clean architecture on the java/GWT side.

    The main advantage I see is that it minimize the size of JS code, and is easy to update with any future bridge between GWT.event and JS events.

    The main issue is that you must be able to have access to your JS code.