matty-d
matty-d

Reputation: 2651

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.

Upvotes: 5

Views: 398

Answers (1)

Stepan Riha
Stepan Riha

Reputation: 1724

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"), ....);
   ...
});

Upvotes: 1

Related Questions