title: How to loop through array of layers in mapbox to listen for a click event?
body: <p>I am newbie to Mapbox API and I am trying to develop something in which geojson files are returned from the server and the features are plotted on the map.</p>
  
  <p>I am successful in plotting features on the map. What I do is look through all records and see if the geojson column has a value and if it does I fetch it from the server, make a new layer and plot it on that layer.</p>
  
  <p>These are all polygons. What I need to do is to fire an event when I click on one of the polygons which is why I am using individual layers. Here is the code:</p>
  
  <pre><code>&lt;script type="text/javascript"&gt;
          L.mapbox.accessToken = 'someKey';
          var map = L.mapbox.map('map', 'someMap')
              .setView([-39.67, -69.26], 4);
  
          $(document).ready(function(){
              $('header h2').text('Equipment Map');
  
              $.getJSON('distributor-companies', function (data) {
                  var layers = [];
                  $.each(data, function(i, item) {
                      if(item.geojson != ''){
                          var file = item.geojson;
                          layers[i] = L.mapbox.featureLayer().addTo(map);
                          $.getJSON('/geojson/' + file, function(data){
                              console.log('layer' + i);
                              layers[i].setGeoJSON(data);
                          });
                      }
                  });
                  $.each(layers, function(i, item){
                      console.log(item);
                      // item.on('click', function(e){
                      //  alert('hello');
                      // });
                  });
  
                  layers[32].on('click', function(e){
                      alert('hello');
                  });
                  layers[31].on('click', function(e){
                      alert('hello hi');
                  });
              });
          });
      &lt;/script&gt;
  </code></pre>
  
  <p>Now I take all the data from the distributor-companies route and make a new layer each time and plot data for every record. So at the end I am left with a lot of polygons.</p>
  
  <p>In the end I am trying to individually register a click event listener on the layers which is working perfectly. But the code just before that where I am trying to loop through the layer is not working. The console.log function is showing me all the layers as object but when I try to register an on click event on the item it doesn't work and my console says TypeError item is undefined but console.log is working fine with it.</p>
  
  <p>Clearly I am not a JavaScript expert and don't realize what am I doing wrong. I just need to loop through all the layers and place an onclick event on them.</p>