Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Hide global window.google.maps object with AMD

I'm using the AMD module pattern and until now, it has been relatively simple to hide what would otherwise be global objects:

define([], function(){

  /*jquery here */

  var tmp = $;
  $ = undefined;
  return tmp;
}

However, I'm curious if it's possible to do something similar with google's global objects (I guess they're really into these.. maps and pretty much any of its APIs use em).

Just doing what I've done before actually breaks the code because. It seems internally google is self referencing itself with calls to the global window.google object from scripts it loads on the fly.

I'm going to keep investigating but am curious what you all think!

Thanks.

like image 206
matty-d Avatar asked Nov 10 '22 11:11

matty-d


1 Answers

If you're using RequireJS as your AMD loader, you can use config shims to wrap non-AMD modules, express their dependencies, perform any necessary initializations (where you could clear their global, if the script supports it) and export their global.

For Google Maps, this would look something like this (and no, you probably don't want to clear the global google variable):

require.config({
    paths: {
        "maps": "https://maps.googleapis.com/maps/api/js?key=API_KEY"
    },
    shims: {
        "maps": {
            exports: "google.maps"
        }
    }
});

Later on, you can use this as a regular AMD module:

require(["maps"], function(maps) {
   var map = new maps.Map(document.getElementById("map-canvas"), ....);
   ...
});
like image 74
Stepan Riha Avatar answered Nov 14 '22 21:11

Stepan Riha