我最近使用钛合金开发了一个android应用程序。现在我尝试(第一次)使用比较器函数按距离对绑定(bind)的 Backbone 集合进行排序,但它不起作用。
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;
}
}
在我的 Controller 中,我使用:
var games = Alloy.Collections.allGames;
games.sort();
games.fetch();
你能告诉我出了什么问题吗?
最佳答案
我既不使用钛合金,也不使用合金,但我明白为什么你的比较器功能不起作用。
主干集合的comparator
属性
首先,要了解它为什么不起作用,您需要了解集合的 comparator
属性是什么、可用的属性以及如何实现。
集合的 comparator
属性可以采用(至少)3 种类型的值。
字符串形式的属性名称
comparator: 'fieldName'
A
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')); }
A 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; }
为什么你的失败了?
简短的回答:它只会返回 undefined
或 0
,具体取决于 Ti.Geolocation.locationServicesEnabled
的值。
您已经创建了一个复杂的函数来对使用异步函数(getCurrentPosition
、forwardGeocoder
)的模型进行排序,并将所有逻辑放入回调中,这些逻辑在以下情况下进行评估:该集合已完成排序。
关于javascript - 按距离与钛合金型号排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39816171/