JS modules - ReferenceError: <function> is not defined

Viewed 1886

I'm trying to import a js function from an external .js file using the "module" type but I keep getting the error "ReferenceError: polygonClick is not defined".

Here's my code:

HTML:

<!DOCTYPE html>
<html>
  <head>
    ...
    <script src="js/map.js" type="module"></script>
  </head>
  <body>
    ...
    <script>
      function initMap() {
        ...
        $.getJSON( "./DI.json", function( coords ) {
            var building = new google.maps.Polygon({...});
            building.setMap(map);

            building.addListener('click', (event) => polygonClick(event));
        });
        ...
      }
    </script>
  </body>
</html>

JS:

import {MDCDrawer} from './@material/drawer';

export default { polygonClick };

const drawer = MDCDrawer.attachTo(document.querySelector('.mdc-drawer'));

function polygonClick(event) {
    console.log(event); 
}

Can someone tell me what I'm doing wrong pls?

Thank you in advance!

1 Answers

It is because the js code inside your module is not global, so the function initMap() is not global. Simpy, make it global this way:

window.polygonClick = function(event){
    //you function code
}

The window. will make the variable or the function global in the context.

Related