我目前正在開發一個GWT項目,現在需要使用外部JavaScript文件。我現在正在創建一個測試原型,以確保雙方工作正常。使用GWT JSNI與js文件集成
當我運行和編譯時,我看到控制檯從被調用的事件中登錄瀏覽器。但是,GWT java方法沒有被調用。
在嘗試了很多場景之後,我還注意到如果從exportStaticMethods()
中刪除$entry
包裝,則會發生相反情況。我看到在我的java代碼中調用了System.out
,但是瀏覽器中JavaScript的控制檯日誌沒有被調用。
我想找出是什麼導致的行爲,如果有一個小的遺漏件,我忽略了。
我已經檢查了GWT JSNI文檔calling a Java method from js並試圖從StackOverflow上的其他相關問題找到解決方案。
GWT和Java方面
我已經爲我的EntryPoint
類的onModuleLoad()
方法,並添加了一個名爲exportStaticMethods()
靜態方法。我還創建了下面列出的PokePingClass.java
文件。
EntryPointClass.java
public class EntryPointClass implements EntryPoint {
@Override public void onModuleLoad() {
exportStaticMethods();
// load application here.
}
public static native void exportStaticMethods() /*-{
$wnd.pingApp = $entry((function) {
@com.application.PokePingClass::pingApp()();
});
$wnd.pokeApp = $entry((function) {
@com.application.PokePingClass::pokeApp()();
});
}-*/
}
PokePingClass.java
public class PokePingClass {
public static void pokeApp() {
System.out.println("pokeApp() called");
}
public static void pingApp() {
System.out.println("pingApp() called");
}
}
HTML和JS
在.html
文件的項目,我加號的隱藏div
元素「 pokePing',以及pokeping.js
文件。
<html>
<head>
.
. <!-- other stuff -->
.
<script type='text/javascript' src='pokeping.js</script>
</head>
<body>
.
. <!-- other stuff -->
.
<div id="pokePing" style="visibility: hidden;"></div>
</body>
</html>
pokeping.js
$(document).ready(function) {
var $pp = $('#pokePing');
var pokeApp = function() {
console.log("app handling poke event");
window.parent.pokeApp();
}
var pingApp = function() {
console.log("app handling ping event");
window.parent.pingApp();
}
$pp.trigger('pokeApp');
$pp.trigger('pingApp');
}
道歉。我更正了函數的JSNI語法。我仍然在觀察同樣的問題。我忘了注意我也在使用jquery-2.2.4.min.js。如果有幫助,它目前不在沒有衝突模式下運行。這個問題也在SmartGWT論壇中被交叉引用,因爲我也在使用該框架。 – JEberhardt
除了未被調用的方法之外,瀏覽器的控制檯中沒有其他錯誤嗎?你確定System.out能夠完成你認爲它在瀏覽器中的作用嗎? –
對不起,遲到回覆。我在SO上找到了類似的答案。我找不到OP,但會在我遇到它時提供鏈接。由於某些原因,當我添加一個返回JSNI函數時,它似乎工作,我看到System.out語句。 – JEberhardt