1

I'm using the Gmaps.js api in a little project I'm building and struggling with adding click events within a for loop. Here's the code:

for(var i = 0; i < number; i++) {
        var entryTime = data[i].datetime;
        map.addMarker({
            lat: data[i].lat,
            lng: data[i].lng,
            click: function(){
                alert(entryTime);
            }
        });
}

However, when clicking the markers I always get the last data element. How can I bind this function to each marker?

1 Answer 1

1

This is the expected behavior. The entryTime variable is defined and changed outside the click handler; and when the click handler is fired it will alert the last value assigned to entryTime.

One solution is to create a closure in order to create a copy of variables and their values at the time the closure was created.

for (var i = 0; i < number; i++) {
    map.addMarker({
        lat: data[i].lat,
        lng: data[i].lng,
        click: (function (t) {
            return function () {
                alert(t);
            };
        })(data[i].datetime)
    });
}

The details are explained in this question.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.