title: Trouble understanding closures/scope in nested events in javascript
body: <p>I'm writing an app in angular and have to determine whether or not a layer can be loaded as GPX or KML (geographic data XML files). Then I return the layer that it was successfully loaded as. However, I cannot for the life of me figure out how to set a variable to true when I am within the .on(ready) event (the success event). Here is my code:</p>
  
  <pre><code>(function() {
  'use strict';
  
  angular
      .module('TractNotes')
      .factory('xmldataService', xmldataService);
  
  xmldataService.$inject = [];
  
  /* @ngInject */
  function xmldataService() {
      var isKML = false;
      var isGPX = false;
  
      var service = {
          getxmldata: getxmldata
      };
      return service;
  
      ////////////////
  
      function getxmldata(layer) {
          var kml = omnivore.gpx('this will fail')
              .on('ready', function() {
                  isKML = true;
              })
              .on('error', function() {
                  console.log("This is not a KML layer.")
              })
  
          var gpx = omnivore.gpx(layer)
              .on('ready', function() {
                  isGPX = true;
              })
              .on('error', function() {
                  console.log("This is not a GPX layer.")
              });
  
          if(isKML){
              return kml;
          }
          else if(isGPX){
              return gpx;
          }
          else{
              return 'invalid file';
          }
          // @TODO: use desc xml tag as layer name
      }
  }
  })();
  </code></pre>
  
  <p>When the code runs, the console.logs work correctly BUT it never returns anything because the booleans are never properly set. Any help understanding this is appreciated.</p>
  
  <p>leaflet-omnivore docs: <a href="https://github.com/mapbox/leaflet-omnivore" rel="nofollow">https://github.com/mapbox/leaflet-omnivore</a></p>