2011-12-10 120 views
0

我不知道如果我真的很愚蠢或錯過了一些東西,但基本上我試圖訪問變量緯度,並將其放入params變量,所以我可以發送它在一個post請求,但它似乎並沒有工作,如果我警告變量緯度之前params函數之外我給它分配一個值警報返回空白。我的代碼如下所示:鈦手機,並不能獲得價值的外部功能

var latitude; 



    Titanium.Facebook.requestWithGraphPath('me', {}, 'GET', function(e) { 
       if (e.success) { 
        var user = eval('('+e.result+')'); 

        var currentTime = new Date(); 
        var hours = currentTime.getHours(); 
        var minutes = currentTime.getMinutes(); 
        var month = currentTime.getMonth() + 1; 
        var day = currentTime.getDate(); 
        var year = currentTime.getFullYear();            

        if (Ti.Geolocation.locationServicesEnabled) { 
         Titanium.Geolocation.purpose = 'Get Current Location'; 
         Titanium.Geolocation.getCurrentPosition(function(e) { 
          if (e.error) { 
           alert('Error: ' + e.error); 
          } else { 
           latitude = e.coords.latitude; 
           longitude = e.coords.longitude; 
           accuracy = e.coords.accuracy; 
          } 
         }); 
        } else { 
         alert('Please enable location services'); 
        } 

        alert(latitude); 

        var params = { 
         username: user.username, 
         gender: user.gender,  
         lastOnline:day+"/"+month+"/"+year+" - "+hours+":"+minutes, 
         latitude:latitude, 
         //longitude:longitude, 
         //accuracy:e.coords.accuracy, 
        }; 

回答

1

很確定這是標準的「期望異步函數同步行爲」問題。雖然我不熟悉titanium-mobile,但我猜Titanium.Geolocation.getCurrentPosition是一個異步函數 - 這意味着您指定的回調函數在執行下一個語句alert(latitude);時不會運行。

要解決這個問題,你需要確保任何需要被設置在回調函數,而不是之前被調用地理位置:

Titanium.Geolocation.getCurrentPosition(function(e) { 
    if (e.error) { 
     alert('Error: ' + e.error); 
    } else { 

     var params = { 
      username: user.username, 
      gender: user.gender,  
      lastOnline: day+"/"+month+"/"+year+" - "+hours+":"+minutes, 
      latitude: e.coords.latitude, 
      longitude: e.coords.longitude, 
      accuracy: e.coords.accuracy 
     }; 

     // now do something with params 
     initializeStuff(params); 
    } 
}); 
+0

而是試圖在那麼不會我得到了同樣的問題訪問參數?但是我可以在功能內做任何我需要的功能我只是想在將來我可能需要從功能外訪問它 –

+0

只要您確定回調已經返回,就可以從回調之外訪問它。請參閱我的上述編輯 - 這裏常見的方法是,當您要異步獲取所需的信息時,將啓動回調主體中的初始化函數。 – nrabinowitz