DukeScript: How do native calls into JavaScript work?

丶灬走出姿态 提交于 2019-12-13 07:25:36

问题


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:


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.



来源:https://stackoverflow.com/questions/30631969/dukescript-how-do-native-calls-into-javascript-work

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!