2

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 ?

Brian Tompsett - 汤莱恩
  • 5,753
  • 72
  • 57
  • 129
Anthony Richir
  • 649
  • 2
  • 8
  • 31
  • Is this of any help http://stackoverflow.com/questions/2951621/gwt-custom-events/2967359#2967359 – Abhijith Nagaraja Mar 06 '13 at 12:05
  • Unfortunately not as it explains how to handle events triggered from within the application, in Java (but maybe one can fire an event from JSNI). In my case, the javascript event would be triggered from outside the application, from another component on the page or from the browser itself as the module will be displayed in an embedded XULRunner in an Eclipse RCP application. – Anthony Richir Mar 07 '13 at 08:11

1 Answers1

2

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.

Sepod
  • 36
  • 4