2012-07-21 74 views
2

我正在使用W3C Geolocation API來檢索GWT Web應用程序中的位置信息。地理位置API是在回調位置位置後立即調用回調函數的方式構建的。從GWT的內部函數調用Java方法JSNI

我目前的測試代碼如下:

public native void getCoordinates() /*-{ 
    function onPositionUpdate(position) { 
     var lat = position.coords.latitude; 
     var lng = position.coords.longitude; 
     var alt = position.coords.altitude; 

     // not OK,- doesn't get invoked, and function execution stops at this point 
     [email protected]::testMethod()(); 

     alert("Coordinates retrieved: " + lat + ";" + lng + ";" + alt); 
    } 

    function onPositionUpdateFailed(error) { 
     alert("Some error"); 
    } 

    if(navigator.geolocation) { 
     // OK when invoked somewhere here 
     [email protected]::testMethod()(); 

     navigator.geolocation.getCurrentPosition(onPositionUpdate, onPositionUpdateFailed); 
    } else { 
     alert("Geolocation is not available"); 
    } 
}-*/; 

我試圖證明testMethod沒有得到來自內部方法onPositionUpdate調用的方法。甚至更多:之後沒有顯示警報(它在刪除testMethod調用時顯示),但是在日誌中沒有發現警告或錯誤。

我的問題是:如何從內部函數引用此方法?我覺得this.不是內部函數的正確參考。如果Java類無法正確引用,那麼可能的解決方法是什麼?請注意,我不能通過任何其他功能onPositionUpdate(),因爲它是一個回調函數。

回答

8

this當函數定義之內時,你的javascript在JSNI塊內被實際執行。

添加封閉周圍this

public native void getCoordinates() 
/*-{ 

    var that = this; 

    function onPositionUpdate(position) { 
     var lat = position.Wecoords.latitude; 
     var lng = position.coords.longitude; 
     var alt = position.coords.altitude; 

     [email protected]::testMethod()(); 

     alert("Coordinates retrieved: " + lat + ";" + lng + ";" + alt); 
    } 

    // ... 
}-*/; 

我相信這是在谷歌的JSNI文檔記錄的地方,至少在路過的例子,但現在我不能找到它。

這也可以通過使一個實例通過給javascript注射來完成,例如:

public native void getCoordinates(com.test.GpsPanel instance) 
/*-{ 

    function onPositionUpdate(position) 
    { 
     var lat = position.Wecoords.latitude; 
     var lng = position.coords.longitude; 
     var alt = position.coords.altitude; 

     [email protected]::testMethod()(); 

     alert("Coordinates retrieved: " + lat + ";" + lng + ";" + alt); 
    } 

    // ... 
}-*/; 
+0

可以通過我們com.test.GpsPanel 作爲com.test.GpsPanel取代例如@ com.test.GpsPanel :: TestMethod的()(); – 2013-11-28 08:15:53

3

導致相同的行爲的相關瑣碎的錯誤是在調用Java方法時常常忘記第二對括號。第一對用於重新標識方法頭,用於標識目的,而第二對包含實際參數。當沒有參數時,這個錯誤特別容易實現,例如

[email protected]::testMethod()();