[英]Using Javascript closure to pass additional data to an API callback function
我已经让这个工作了一点但似乎无法弄清楚使for
循环传递正确值的确切措辞是什么。
for(i=0; i < the_stores.length; i++) {
uid = the_stores[i].id;
// get the lat long and write info to the console
geocoder.getLatLng(the_stores[i].address, function(point) { return callbackFunc(point, uid); });
}
function callbackFunc(point, myID) {
if(point !== null) {
console.log(point.toString());
console.log(myID);
} else {
return false;
}
}
我正在使用Google Maps API,v2。 我希望for循环将uid
的不同值传递给循环中每次迭代的回调函数,但是现在它每次都传递相同的值。 谁知道如何在这里获得所需的效果? 我觉得我很亲密。 谢谢!
使用您的callbackFunc
返回一个处理程序,该处理程序引用需要保留的值。
for(i=0; i < the_stores.length; i++) {
// get the lat long and write info to the console
geocoder.getLatLng(the_stores[i].address, callbackFunc(the_stores[i].id));
}
function callbackFunc(myID) {
return function(point) {
if(point !== null) {
console.log(point.toString());
console.log(myID);
} else {
return false;
}
};
}
这就是我喜欢Array.forEach()
原因。 它会为您解决循环中的所有这些常见问题。 像这样使用它:
the_stores.forEach(function (store, i) {
geocoder.getLatLng(store.address, function(point) {
return callbackFunc(point, store.id);
});
}
Array.forEach()
是现代浏览器中的原生JavaScript,但对于IE8和IE7,您需要自己添加它。 我建议使用MDN提供的实现 。 以我的拙见,至少包括所有新Array
方法的JS5填充程序应该是任何网站的模板。
您正在寻找的是“立即调用函数表达式”。 由于JavaScript只有函数作用域而不是块作用域,因此对uid
所有引用都绑定到同一个变量。
(有关更多信息,请参阅: http : //benalman.com/news/2010/11/immediately-invoked-function-expression/ )
这是一种简单的方法:
for(i=0; i < the_stores.length; i++) {
(function() {
var uid = the_stores[i].id;
// get the lat long and write info to the console
geocoder.getLatLng(the_stores[i].address, function(point) { return callbackFunc(point, uid); });
})();
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.