Search code examples
gwtgwt-jsinteropgwt-elemental

Gwt elemental2: How can I convert between a gwt JavaScript object, and a JsInterop object?


Lets say I have a com.google.gwt.dom.client.Document gwtDocument node and I want to convert it to a elemental2.dom.Document?

Since Document extends JavaScriptObject I assumed I could do something like:

elemental2.dom.Document elementalDoc = (elemental2.dom.Document)(gwtDocument);

However the elemental2 classes using jsinterop don't extend JavaScriptObject. So how do I convert between the two?

Thanks!


Solution

  • You can first cast to object, and then cast to the elemental type (1). This is a bit ugly, so there is a utility lib that can be used in GWT and J2CL called jsinterop-base. The Js utility can be used to cast(2) and uncheckedCast(3) any object. The uncheckedCast should be avoided and only used if you know what you are doing (ex. casting between iframes, or other special js situations).

    com.google.gwt.dom.client.Document gwtDocument = Document.get();
    elemental2.dom.Document el1 = (elemental2.dom.Document) (Object) gwtDocument; //(1)
    elemental2.dom.Document el2 = jsinterop.base.Js.cast(gwtDocument); //(2)
    elemental2.dom.Document el3 = jsinterop.base.Js.uncheckedCast(gwtDocument); //(3)
    

    So in client code, you should use Js.cast to cast GWT dom instances to elemental2 instances.