- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
以下问题:我有一个带有 $http.get
的 Angular 模块来获取一些谷歌坐标。该函数触发另一个函数。该函数再次触发另一个函数。一会儿一切都会变得有意义。
Angular 模块:
var myApp = angular.module('wmw', []);
myApp.controller('MainCtrl', function ($scope, $http) {
//Angular Method
$scope.getTargetCords = function (data) {
$http.get(data).success(function (response) {
$(document).triggerHandler('my_func:data-received', [response]);
});
};
});
成功时:
var onSuccess = function(position) {
currentLat = position.coords.latitude ;
currentLng = position.coords.longitude;
for(i = 0; i<locations.length;i++){
var destUrl = 'http://maps.googleapis.com/maps/api/geocode/xml?address=' + locations[i][ 'street' ] + ',' + locations[i][ 'city' ] + ',Deutschland' + '&sensor=true';
var MyAngularScope = angular.element($("#MainCtrlId")).scope();
MyAngularScope.getTargetCords('http://maps.googleapis.com/maps/api/geocode/xml?address=' + locations[i][ 'street' ] + ',' + locations[i][ 'city' ] + ',Deutschland' + '&sensor=true');
}
};
navigator.geolocation.getCurrentPosition(onSuccess, onError);
两个触发器:
$(document).on('my_func:data-received', function(event, response) {
map[s] = response;
s++;
if(s === locations.length){
$(document).triggerHandler('allData');
}
});
$(document).on('allData', function(){
var thecoords = [];
var distance = [];
$('#filter-list').empty();
for(var i = 0; i < locations.length; i++){
thecoords[0] = $(map[i]).find('lat').first().text();
thecoords[1] = $(map[i]).find('lng').first().text();
distance[i] = calculateDistance(currentLat, currentLng, thecoords[0], thecoords[1]);
locations[i]['distance'] = distance[i];
}
locations.sort(function(a,b)
{ return a.distance - b.distance;}
);
for(var i = 0;i < locations.length; i++){
distance[i] = locations[i]['distance'].toFixed(2);
distance[i] += ' KM';
locations[i]['distance'] = distance[i];
}
$('.loading').hide();
for(var i = 0; i<=5; i++){
addItemToList(locations[i]);
}
});
发生什么事了?通过这些函数,我可以检索当前位置、目标位置,并通过纬度/经度计算公里差。 calc 函数是我在网上找到的。 .loading
只是一个带有“计算路线...”和透明灰色背景的 div。因此,一旦一切完成,每条路线的“距离”将更改为计算出的距离。
问题在于:在我的“.on('my_func:data-received')”中,我使用变量“s”,该变量开头为 0。按照我的逻辑,我认为这会将响应一个接一个地放入我的“ map ”中。但现在我意识到,“数据接收”不是一次又一次地调用,而是每次检索数据时调用。因此,当locations[0]调用$http.get
,然后在此locations[1]调用$http.get
之后,可能会发生locations[ 1]提前检索数据。我怎样才能让我的“s”始终是正确的数字?这样,当我有locations[1]调用$http.get
时,map[1]将是locations[1]响应?
我的头爆炸了,因为我找不到解决这个问题的方法,尽管它看起来很基本。
提前谢谢您!
最佳答案
由于重组应用程序不是一种选择,因此获得正确顺序的另一种相当快速的方法是将响应数据映射到原始数组。响应包含使用数组中的数据构建的 url,这可能会为您提供所需的内容。
关于javascript - 如何为延迟触发获得正确的索引?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29076393/
我是一名优秀的程序员,十分优秀!