如何从我正在使用的result()回调函数中捕获返回值?

时间:2011-03-15 18:13:22

标签: javascript callback anonymous-function

<script type="text/javascript">
  var geo = new GClientGeocoder();

  function showAddress() {
    var search = document.getElementById("search").value;
    // getLocations has not ret, so wtf!
    geo.getLocations(search, function (result) { (result.Status.code == 200) ? alert(result.Placemark[0].Point.coordinates) : alert(result.Status.code); });
  }</script>

我需要回调的ret值,因为getLocations()不返回任何值。我怎么能这样做?

1 个答案:

答案 0 :(得分:2)

你做不到。您必须编写代码,以便在回调中执行需要result值的代码。

示例(我只是以对我来说合乎逻辑的方式命名函数):

function drawPlacemarks(marks) {
   // do fancy stuff with the results
   alert(marks[0].Point.coordinates);
}

function getAddress(callback) {
    var search = document.getElementById("search").value;
    geo.getLocations(search, function (result) { 
        if(result.Status.code == 200) {
           // pass the result to the callback
           callback(result.Placemark);
        }
    });
}

getAddress(drawPlacemarks);