0

I'm getting back an array of JavaScript objects from a database. I'm looping through that array and creating objects to be displayed on the screen. I'm trying to use .addEventListener() to each object but I just realized that addEventListener() only works for DOM objects.

How could I add an event listener to each JavaScript object?

Here is my code:

    var objects = JSON.parse(data.responseText);
    var i;
    var objectLn = objects.length;

    for (i = 0; i < objectLn; i++) {

        //Puts each object into a variable
        var eachObject = objects[i];

        //Establishes pin position
        var pinPos = {
            lat: parseFloat(eachObject.lat),
            lng: parseFloat(eachObject.lng)
        };

        //Creates new icon for pin
        var icon = {
            url: "path/to/img",
            scaledSize: new google.maps.Size(60, 60),
            origin: null,
            anchor: null
        };

        //Creates a new pin from pulled information
        var pin = new google.maps.Marker({
            position: pinPos,
            map: map,
            icon: icon
        });

        //Alerts each object on click
        pin.addListener('click', function() {
            alert(JSON.stringify(eachObject));
            map.panTo(pinPos);
            map.setCenter(pinPos);
        });
    }

addListener is adding a 'click' listener to each pin that is dropped, so that's good. The problem is that it's supposed to alert each object, but it's only alerting the last object I retrieve from the database on every pin I click.

12
  • How are you displaying these objects on screen if not using the DOM? Commented Feb 29, 2016 at 20:11
  • 1
    what kind of events are you hoping to listen for? Commented Feb 29, 2016 at 20:12
  • @Pamblam I was looking to add 'click' events to each one Commented Feb 29, 2016 at 20:15
  • you can't click on an object. so it doesn't make much sense to add a click event to one. Commented Feb 29, 2016 at 20:16
  • 1
    eachObject is being overridden on each iteration, for loops don't have their own scope (unless using es2015 let and const) the array forEach method would be more suitable than a for loop. Commented Feb 29, 2016 at 20:45

1 Answer 1

1

try doing your loopage like so..

for (i = 0; i < objectLn; i++) {
    (function(eachObject){
        // copy the loop contents here. eachObject is already defined.
    })(objects[i]);
}
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.