2016-10-02 49 views
0

我最近使用鈦合金來開發Android應用程序。現在我試着(第一次)用比較函數按距離排序綁定的骨幹集合,但它不起作用。與鈦合金模型按距離排序

comparator: function(game) { 
    var lon1, lat1, lat2, lon2; 
    if (Ti.Geolocation.locationServicesEnabled) { 
     Ti.Geolocation.getCurrentPosition(function(e) { 
      if (e.error) { 
       Ti.API.error('Error:' + e.error); 
       return 0; 
      } else { 
       Ti.API.info(e.coords); 

       lon1 = e.coords.longitude; 
       lat1 = e.coords.latitude; 

       Titanium.Geolocation.forwardGeocoder(game.get("camp"), function(e) { 
        if (e.success) { 
         lat2 = e.latitude; 
         lon2 = e.longitude; 

         var R = 6371; // km 
         var dLat = (lat2 - lat1) * Math.PI/180; 
         var dLon = (lon2 - lon1) * Math.PI/180; 
         var a = Math.sin(dLat/2) * Math.sin(dLat/2) + 
          Math.cos(lat1 * Math.PI/180) * Math.cos(lat2 * Math.PI/180) * 
          Math.sin(dLon/2) * Math.sin(dLon/2); 
         var c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1 - a)); 
         var d = R * c; 

         console.log("KM: " + parseInt(d)); 

         return parseInt(d); 
        } else { 
         console.log("Unable to find address"); 

         return 0; 
        } 
       }); 
      } 
     }); 
    } else { 
     console.log('please enable location services') 

     return 0; 
    } 
} 

在我的控制,我使用:

var games = Alloy.Collections.allGames; 
games.sort(); 
games.fetch(); 

你能告訴我什麼是錯?

回答

1

我不使用鈦或合金,但我可以看到爲什麼你的比較器功能不起作用。

骨幹集合的comparator財產

首先,要明白爲什麼它不工作,你需要了解什麼是集合的comparator財產,什麼是可用的,以及如何實現一個。

有(至少)3種類型的價值屬性可以採取的集合的comparator

  • 作爲字符串

    comparator: 'fieldName' 
    
  • sortBy函數,它接受一個參數的屬性的名稱

    comparator: function(model) { 
        // return a numeric or string value by which the model 
        // should be ordered relative to others. 
        return Math.sin(model.get('myNumber')); 
    } 
    
  • sort功能需要兩個參數

    comparator: compare(modelA, modelB) { 
        var field = 'myNumber', 
         numA = modelA.get(field), 
         numB = modelB.get(field); 
        if (numA < numB) { 
         return -1; 
        } 
        if (numA > numB) { 
         return 1; 
        } 
        // a must be equal to b 
        return 0; 
    } 
    

爲什麼你的失敗?

簡短回答:它只會返回undefined0,具體取決於Ti.Geolocation.locationServicesEnabled的值。

你做出了一個令人費解的功能,在您使用異步函數(getCurrentPositionforwardGeocoder)你的模型排序和你把所有的邏輯裏面集合時已經整理完這些評估的回調。

+1

我明白,很多! – Luca4k4