JsInterop wrapping a javascript function property

2019-07-30 17:17发布

问题:

I am working with GWT 2.8, and I am working on a wrapper for a javascript library.

One of the properties of a javascript class I am trying to wrap is a function. I would like the wrapper to work as closely as possible to the native javascript. How do I go about wrapping a JsProperty that is a javascript function?

Details: The javascript class has a property that is a function that is called when a specific event is triggered. I would like to be able to write a labmda function in Java, and assign it to this property, which would then run in javascript.

回答1:

As Adam said (and explained in more detail in the other post), you can expose a @JsProperty with a @JsFunction type.

@JsType(isNative=true) public class Foo {
    @JsFunction public static interface BarFn {
        Object invoke(Object... args);
    }
    @JsProperty public BarFn bar;
}

My recommendation to learn JsInterop is to explore other projects like: OpenLayers JsInterop wrapper, Elemental2 source code, or explore github. Elemental2 has the whole browser API so there are plety of examples, it is a really good place to find examples. JsInterop documentation here.