DukeScript: How do native calls into JavaScript work?

250 views Asked by At

I'm struggling to understand how "native method" calls in DukeScript work. In particular, the ones where no body is specified in the @JavascriptBody annotation. For example:

@JavaScriptResource(value = "userEntryComponent.js")
public final class UserEntryWidget {

    private UserEntryWidget() {
    }

    @JavaScriptBody(args = {}, body = "")
    public static native void registerComponent();
}

Where is the "registerComponent()" method defined? In knockout there's a javascript function called "ko.components.register". So "registerComponent" must be a sort of wrapper around "ko.components.register".

Another example of a native method call without body is here:

@JavaScriptResource("jquery-1.11.0.min.js")
public class JQuery {

    @JavaScriptBody(args = {},body="")
    public static native void init();   
}

So, in this case, what's "init()"? is it a Java method or a JavaScript function?

1

There are 1 answers

3
Jaroslav Tulach On BEST ANSWER

I fully understand why the code looks magical. However if you try to comment out the init method, you should see error during javac complication:

COMPILATION ERROR : 
-------------------------------------------------------------
JQuery.java:[10,8] At least one method needs @JavaScriptBody
annotation. Otherwise it is not guaranteed the resource will
ever be loaded

The error line is the line with @JavaScriptResource usage. The init method definition is really empty and does nothing. But once called, it enforces load of resource defined in @JavaScriptResource.

In the knockout case, the ko.components.register is defined by the knockout.js resource file. The method name registerComponent can be arbitrary, it is there to just trigger the load of the knockout.js resource.