Chuan Yeong
Chuan Yeong

Reputation: 3639

Function invocation in javascript

I am working on a small webapp that uses google maps api.

At one point I wanted to place markers and attach event listener to it.

//initialization of infowindow and markers
var points = [];
var infowindow = new google.maps.InfoWindow({
    content: "1234"
});

function addInfoWindow(point){
    infowindow.setContent(point.position + " " + point.title),
    infowindow.open(map, point);
}

Here's the problem, when I initiate markers with

//initialize markers
{% for marker in mapMarkers %}
    points[{{ marker.id }}] = new google.maps.Marker({
        position: new google.maps.LatLng({{ marker.geometry.y }},
            {{ marker.geometry.x }}),
        map: map,
        title: '{{ marker.name }}',
        clickable: true
    });

    //add event llistener for infowindow
    points[{{ marker.id }}].content = "abc"
    //look here!!
    google.maps.event.addListener(points[{{ marker.id }}], 'click',
        addInfoWindow(points[{{ marker.id }}])
    );
{% endfor %}

It would instantly show infowindow from the first marker. The other markers were placed but clicking on them never produce any changes.

While if I do this

    google.maps.event.addListener(points[{{ marker.id }}], 'click',
    function(){
        addInfoWindow(points[{{ marker.id }}])
    });

Stuffs works perfectly fine, infowindow only appears when marker was clicked.

My question: why is there a need to use

function(){}
instead of directly using addInfoWindow. I figured it might be an issue of function invocation where addInfoWindow calls the global variable, but if that's the case, the infowindow that shows up should display information from the last marker instantiated right?

Upvotes: 1

Views: 88

Answers (1)

raina77ow
raina77ow

Reputation: 106375

Because you need to assign a function as a click handler - and you do that with...

google.maps.event.addListener(points[{{ marker.id }}], 'click',
function(){
    addInfoWindow(points[{{ marker.id }}])
});

... as this will create an anonymous function (with call to addInfoWindow in its body).

But with this...

google.maps.event.addListener(points[{{ marker.id }}], 'click',
    addInfoWindow(points[{{ marker.id }}])
);

... you try to assign the result of addInfoWindow call as event handler, not the function itself. Of course, it doesn't work.

Upvotes: 2

Related Questions