Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
360 views
in Technique[技术] by (71.8m points)

knockout.js - DukeScript: How do native calls into JavaScript work?

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...