1

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;
mplungjan
  • 169,008
  • 28
  • 173
  • 236
shafe
  • 11
  • 3
  • Please update the snippet I made for you with relevant HTML and script to make a [mcve]. Click [edit](https://stackoverflow.com/posts/52741260/edit) and scroll down to "Edit above snippet" – mplungjan Oct 10 '18 at 13:24
  • This has nothing to do with closures. Remove the unnecessary IIFE and the `funcs` array. The problem is that you define `var contentString = "";` *inside* the loop. Put it before, and concatenate (`+=`) as you intended to, instead of overwriting `contentString = …;`. – Bergi Oct 10 '18 at 13:36
  • Bergi Thank you ! That was it. – shafe Oct 10 '18 at 14:04

0 Answers0