lxm7 lxm7 - 4 months ago 11
Javascript Question

Passing async values around object literal methods

Unsure of how to pass the returned value of

getLocationsArray
outside of the getLocations method. How would this be done so
setMarkers
method can use it? Of course, im aware when calling methods or vars internally within an object literal i can use
APP.map.setMarkers
for example. Thanks.

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..
}

Answer

$.getJSON will only deliver its result asynchronously, so you cannot use code that expects it to be available immediately. Instead use a callback system.

There is no use in returning a value inside the $.getJSON callback function: it will go to oblivion:

 return getLocationsArray // not useful.

You also refer to a variable getLocationsArray2 that is never initialised.

Instead, you could pass a callback argument:

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..
}
Comments