Google Maps Trouble: Closures & Passing By Reference

前端 未结 2 1272
无人及你
无人及你 2021-01-13 09:37

I\'m having some Google Maps/Javascript problems. I think I know what the trouble is but just don\'t know a way round it.

An example of my problem is here. Whateve

相关标签:
2条回答
  • 2021-01-13 09:44

    Change this:

    google.maps.Event.addListener(marker, infoAction, function() {
          alert(marker.value);
          map.openInfoWindowHtml(point, getResultInfoContent(marker.value));
        });
    

    to this:

    google.maps.Event.addListener(marker, infoAction, (function(marker, point, map) { return function() {
          alert(marker.value);
          map.openInfoWindowHtml(point, getResultInfoContent(marker.value));
        }})(marker, point, map));
    

    This will create the closure you want.

    Split out for clarity:

    var f = function(marker, point, map)
    {
        return function()
        {
            alert(marker.value);
            map.openInfoWindowHtml(point, getResultInfoContent(marker.value));
        }
    }
    
    google.maps.Event.addListener(marker, infoAction, f(marker, point, map));
    
    0 讨论(0)
  • 2021-01-13 10:03

    The above answer is not very intuitive though - as Greg said.

    When you add an event to an object, that object is passed down so you can access it by "this" within the closure. If you replaced "marker.value" with "this.value" your problem would have been resolved. If you need to pass down more stuff, you tie it to the object and pass it down:

    marker.a = 1
    marker.b = 2
    marker.c = 3
    

    Within the closure this.a will be 1 and so on..

    0 讨论(0)
提交回复
热议问题