我可以使用GWT(或脚本#)在Java(或C#)中编写单个函数并将它们编译为JavaScript吗?

我理解GWT的目的,但我想知道我是否可以使用它来编译从
Java
JavaScript的一些函数,只是为了确保我不必用两种不同的语言维护相同的代码.

或者GWT会带来太多的库/支持开销,以使其成为一个合理的选择?

对于未来的项目,我有关于Script#(C#编译器)的相同问题.

跟进:

来自C#的脚本#seems to produce very readable JavaScript(第35-51页有一些C#代码和生成的JS代码的例子).

我发现有一个-STYLE标志可以使GWT输出“漂亮”或甚至“详细”.我仍然不知道发出的JS是否依赖于大型库或者是否涉及其他“陷阱”.

最佳答案 是的,你可以做到这一点.这是从Javascript(
Source)调用它的方法:

How can I call one of my GWT Java methods from my application host page?

In order to accomplish this, you’ll
first need to create a JSNI method
that creates a JavaScript method that
in turn makes the call to your Java
method. In your GWT application’s
onModuleLoad(), you would call that
JSNI method so that the JavaScript
method is defined. From your
application host page you would then
call the created JavaScript method.

Confused yet? It’s actually quite
simple.

The code snippet below shows an
example of this (courtesy of Robert
Hanson):

private native void initPlaylistJS  (PlaylistTable pl) /*-{   
   $wnd.addClipToPlaylist = function (clipId, clipTitle) {
        pl.@com.foo.bar.client.PlaylistTable::addClip(Ljava/lang/String;Ljava/lang/String;)(clipId, clipTitle);
    };
}-*/;

In this example, you would need to
make a call to initPlaylistJS(pl) in
your GWT module’s onModuleLoad(). Once
your GWT application loads, the
JavaScript method is defined and is
callable from outside of the GWT
application.

至于“行李”,GWT编译单个整体文件,因此您不需要包含任何其他内容.

需要注意的另一件事是,根据我的经验,GWT不完全适合在服务器和客户端之间共享代码,因为服务器部分需要成为GWT可编译的,只包括属于emulated JRE或其中的一部分的类.您有可用于编译的源.

点赞