Possible Duplicate:
How to get around the jslint error ‘Don’t make functions within a loop.’
Fair warning, I’m VERY much a beginner. I’m working on a google maps api v3 project (http://jsbin.com/ofepet/9/edit) and I have a “Don’t make functions within a loop” warning on JSBin. I want to fix it but I’m using code that I got elsewhere so I’m struggling to understand exactly what’s going on — particularly with the last 7 lines.
In short, I don’t understand the code well enough to take the function out of the loop. The error comes up on the second to last line.
function setMarkers(map, markers) {
for (var i = 0; i < markers.length; i++) {
var sites = markers[i];
var siteLatLng = new google.maps.LatLng(sites[1], sites[2]);
var marker = new google.maps.Marker({
position: siteLatLng,
map: map,
title: sites[0],
zIndex: sites[3],
html: sites[4],
icon: featureImage
});
var contentString = "Some content";
google.maps.event.addListener(marker, "click", function () {
infowindow.setContent(this.html);
infowindow.open(map, this);
});
}
How do I fix this error?
The warning is actually saying exactly what it means. 🙂 You have a
forloop, and within theforloop you’re creating a function to hand toaddEventListener. That’s frequently (though not always) an error, which is why it gets flagged up.In your case, it would actually be harmless — but it looks as though you can just use one function for all of the elements you’re creating in the loop rather than making more than one. So:
Now you’re just creating the one function per call to
setMarkersand reusing it.