2016-07-13 3 views
0

getLocationsArrayの戻り値をgetLocationsメソッドの外部に渡す方法がわかりません。これはどうすれば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.. 
} 
+0

あなたはあなたの質問をより明確にし、より多くのコードを提供することができますか? – sehrob

+0

'jQuery.getJSON'は約束を返します - それを使用します。 – ankr

答えて

1

$.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.. 
} 
+0

非同期性! ... ffs。ありがとうございました。これに関する他の人(と私)のためのさらなる読書:http://stackoverflow.com/questions/23667086/why-is-my-variable-unaltered-after-i-modify-it-inside-of-a-function-asynchron #answer-23667087 – lxm7

関連する問題