在对象文本方法周围传递异步值
Passing async values around object literal methods
不确定如何在getLocations方法之外传递getLocationsArray
的返回值。如何做到这一点setMarkers
以便方法可以使用它?当然,我知道在对象文字内部调用方法或变量时,例如我可以使用APP.map.setMarkers
。谢谢。
init: function(){
...ETC...
APP.map.getLocations()
APP.map.setMarkers(center, radius, map)
},
getLocations: function() {
$.getJSON('data/json/locations.json', function(data) {
var locations = data
var getLocationsArray = $.map(locations, function(value, index) {
return [value]
})
console.log(getLocationsArray)
return getLocationsArray
})
console.log('getLocationsArray2', getLocationsArray2)
return getLocationsArray2
},
setMarkers: function(center, radius, map) {
**getLocationsArray**.forEach (function (hello) {
..ETC..
}
$.getJSON
只会异步提供其结果,因此您不能使用期望它立即可用的代码。而是使用回调系统。
在 $.getJSON
回调函数中返回一个值是没有用的:它将被遗忘:
return getLocationsArray // not useful.
您还引用从未初始化的变量getLocationsArray2
。
相反,您可以传递一个回调参数:
init: function(){
// ...ETC...
// Pass an (anonymous) callback function to `getLocations`, which
// it will call when the result is available. Then you can call
// `setMarkers` to process that result.
APP.map.getLocations(function (getLocationsArray) {
APP.map.setMarkers(getLocationsArray, center, radius, map);
});
},
getLocations: function(callback) {
$.getJSON('data/json/locations.json', function(data) {
var locations = data
var getLocationsArray = $.map(locations, function(value, index) {
return [value]
})
// If a callback function was provided, then call it now and
// pass it the result.
if (callback) callback(getLocationsArray);
})
},
setMarkers: function(getLocationsArray, center, radius, map) {
// We get the locations array as an argument now, so it is straightforward
// to process it:
getLocationsArray.forEach (function (hello) {
///..ETC..
}
相关文章:
- 异步上传多个文件,而不会相互踩踏
- 通过 blueimp jquery-fileupload 异步上传多个文件
- 使用 jQuery File Upload + Carrierwave + Rails 4 启用异步文件上传
- 将文件异步上传到 MVC.NET
- Google App Engine 异步图片上传
- HTML5异步文件上传,上传的流总是无效的
- 在上传过程中取消异步jquery文件上传
- 用于异步文件上传的PHP代码
- 将回调函数传递给redux异步操作是否被认为是好的做法?
- 无法使用 Ajax.BeginForm() 异步上传文件
- Angular2:异步上传文件数组
- 使用mootools进行异步文件上传
- 在表单中异步上传图像
- 将异步函数中获得的值传递给index.html
- 使用jquery异步上传文件操作
- angularjs ng-resource异步上传
- 是否可以执行异步跨域文件上传
- 在对象文本方法周围传递异步值
- 如何将异步加载的脚本传递给jQuery的getScript
- 如何使用 jQuery 异步上传文件