Search code examples
javascriptjavagwtgwt-jsinterop

Implement Javascript Function Callback with GWT JsInterop


I want to wrap a javascript code like this :

map.addMarker({
        lat: -12.043333,
        lng: -77.028333,
        draggable: true,
        fences: [polygon],
        outside: function(m, f){
          alert('This marker has been moved outside of its fence');
        }
      });

Here how I write it in Java :

@JsType(namespace = JsPackage.GLOBAL, isNative = true, name = "Object")
public class MarkerOptions {
    @JsProperty
    public double lat;

    @JsProperty
    public double lng;

    @JsProperty
    public boolean draggable;

    @JsProperty
    public Polygon fences;

    @JsFunction
    public interface FunctionOutsideParam {
        void outside();
    }

    @JsProperty
    public FunctionOutsideParam outside;
}

But it's not working. Even thou it didn't have any error in my browser console. Anybody know how to make it working for the outside callback function? Thanks and regards.


Solution

  • I finally found a solution. It appears that my java code was inconsistent with my javascript code. Thanks to Colin Alworth for pointing me the inconsistent part. So here is my full code :

    @JsType(namespace = JsPackage.GLOBAL, isNative = true, name = "Object")
    public class MarkerOptions {
        @JsProperty
        public double lat;
    
        @JsProperty
        public double lng;
    
        @JsProperty
        public boolean draggable;
    
        @JsProperty
        public Polygon[] fences;
    
        @JsFunction
        public interface FunctionOutsideParam {
            void outside(Marker m, Polygon[] f);
        }
    
        @JsProperty
        public FunctionOutsideParam outside;
    }
    

    Now whenever I run it, the outside function callback was invocated correctly. Thanks everyone. I hope my answer could help many others developer who tried to figured out how to implement js callback function with GWT JSInterop.