lundi 28 décembre 2020

Is this bad javascript practice? [closed]

My website has multiple pages that use the Google Maps api. Each page uses a different part of the api (e.g. autocomplete, displaying markers etc). However, every page needs to call the initMap() function for the api to be initialized.

maps.js

function initMap() {
  const mapOptions = {
    center: {lat: 0, lng: 0},
    zoom: 7
  };
  window.map = new google.maps.Map(document.getElementById("map"), mapOptions);

  if (typeof callback !== 'undefined') {
    callback(); // defined above html link to maps.js
  }
}

Instead of writing out a different initMap() function for every page, I opted to have it in one .js file which is linked to every page. After initializing the map, the function executes a callback function which is defined in each page's corresponding .js file.

index.js

function autocomplete() {
    var input = document.getElementById('address');
    var options = {
    };
    new google.maps.places.Autocomplete(input, options);
}

As initMap() cannot take parameters, I had to define the callback function's name using a cross-script global variable before maps.js is linked. This variable is different on every page depending what function needs to be run in initMap() after the map is initialized.

<script type="text/javascript" src="js/index.js"></script>
<script> var callback = autocomplete </script> <!-- global variable, defines the callback function (in index.js) to initMap()(in maps.js) -->
<script type="text/javascript" src="js/maps.js"></script>

The code works but is very disjointed. Is there a cleaner way to accomplish this?




Aucun commentaire:

Enregistrer un commentaire