1

Hi sorry if this is a simple question, but I could not figure it out on here

My question is about function scope, my code is as follows:

(function ($, Drupal){
  Drupal.behaviors.map = {
     attach: function (context, settings){
        var map;
        function initMap() {
           map = new google.maps.Map($('#map'), {
              center: {lat: -34.397, lng: 150.644},
              zoom: 8
           });
        }
      }
   };
 })(jQuery, Drupal);

In my theme.libraries.yml I have:

 https://maps.googleapis.com/maps/api/blah&callback=initMap: {type: external, attributes: {async: true}}

But on my console I get:

initMap is not a function

So my question is how to allow callbacks to reference to my function initMap? It works if I do the less optimal way $(document).ready...

  • Drupal.mymodule.initMap or any of the gazillion JS approaches. – user21641 Feb 28 '18 at 18:55
  • 1
    Welcome to Drupal Answers! This is a plain JavaScript question, for which the answer doesn't change just because you are using Drupal. initMap() is a nested function, so outside Drupal.behaviors.map.attach() is not visible, nor accessible. Move it outside the Drupal.behaviors.map object. – kiamlaluno Feb 28 '18 at 19:04
  • @kiamlaluno Thanks! I understood what was going wrong now, fixed. – ARMANDO SILVA Feb 28 '18 at 19:12

Browse other questions tagged or ask your own question.