Rod*_*eas 3 javascript gwt jsni
我正在尝试将大部分原生JavaScript代码从JSNI方法转移到脚本中,并且只是利用本机JSNI方法来调用这些外部方法.
现在我的一个点击处理程序遇到了困难.当用户单击某个特定元素时,JSNI方法会执行一些基于JQuery的动画,然后在回调中调用Java方法.一个简单的例子是这样的:
public native void attachClickHandler(SomeCustomPanel customPanel) /*-{
$wnd.jQuery("#theElement").click(function() {
// some JQuery animation logic here...
$wnd.jQuery("#theElement").animate({ top: "500px" }, 500, function() {
customPanel.@com.something.whatever.client.SomeCustomPanel::doSomething()();
});
// some other code here...
});
}-*/;
Run Code Online (Sandbox Code Playgroud)
这段代码有效.它编译并按预期工作.我想将其转换为外部JavaScript.我尝试了以下内容.我把它放在外部JavaScript中:
function attachClickAction(customPanel) {
$("#theElement").click(function() {
// other stuff...
$("#theElement").animate({ top: "500px" }, 500, function() {
customPanel.@com.something.whatever.client.SomeCustomPanel::doSomething()();
});
// other stuff...
});
}
Run Code Online (Sandbox Code Playgroud)
并修改了这样的原生函数:
public native void attachClickHandler(SomeCustomPanel customPanel) /*-{
$wnd.attachClickAction(customPanel);
}-*/;
Run Code Online (Sandbox Code Playgroud)
但是不正确.JavaScript文件甚至不会加载,因为这不是正确的JavaScript.(Chome的开发工具给我错误消息"Uncaught SyntaxError:Unexpected identifier".)
有没有办法从外部JavaScript文件调用Java方法,而不是从JSNI方法调用?
如果重要的话,我在GWT 2.4中.
答案是否定的,您无法从外部JavaScript函数中显式调用Java方法.
但是,您可以聪明并利用JavaScript允许您将函数本身作为参数传递的事实.
我修改了我的JavaScript函数:
function attachClickAction(callbackFunction) {
$("#theElement").click(function() {
// other stuff...
$("#theElement").animate({ top: "500px" }, 500, callbackFunction);
// other stuff...
});
}
Run Code Online (Sandbox Code Playgroud)
在我的Java代码中,我显式地将Java方法作为回调函数参数传递:
public native void attachClickHandler(SomeCustomPanel customPanel) /*-{
$wnd.attachClickAction(function() {
customPanel.@com.something.whatever.client.SomeCustomPanel::doSomething()();
});
}-*/;
Run Code Online (Sandbox Code Playgroud)
这样,当JSNI方法编译时,它正确地调用doSomething()Java方法,并且该方法调用正确地完全传递给外部JavaScript函数.