Here is a very well know post on stack overflow JavaScript closure inside loops – simple practical example but I can't seems to get my head around with it.
My little script below successfully print out each location on the screen. When I click on the marker on the maps it will bring up the pop up windows and it will display the correct image and the menu inside the info windows. The problem I am facing now is I fail to output if each store has more than one image and menu. For example, If I assigned 2 image and 2 menu to a specific store, the output I got on screen is always the last row from the database. From my understanding, i believe it has to do with JavaScript closure but I am yet to arrive that level of understanding.
var funcs = [];
for (var i = 0; i < locations.length; i++) {
for (var x = 0; x < store.length; x++) {
if (i < store.length) {
if (store.location_id == locations[i].id) {
//alert(gon.store[x].menu);
var contentString = "";
(funcs[x] = function() { //closure
contentString =
'<div id="content1">' +
'<div class="container">' +
'<div class="p-3 mb-6 bg-dark text-white text-center" style="margin-bottom:30px;" >Available Store</div>' +
'<div class="row">' +
'<div class="col">' +
'<img src="' + store.image + ' width="150px" height="150px">' +
'</div>' +
'<div class="col text-center">' +
'<table class="table">' +
'<tbody>' +
'<tr>' +
'<th scope="row">Menu</th>' +
'<td>' +
store.menu +
'</td>' +
'</tbody>' +
'</table>' +
'</div>' +
'</div>' +
'</div>' +
'</div>';
})(x);
}
}
}
//contentString+=contentString;