javascriptjqueryrequirejsamdrequirejs-define

Why is my define call not triggering?


I'm using requireJS and am trying to define a Google maps module.

I'm adding this code to the end of HTML snippet:

$(document).ready(function() {
  console.log("ready");
  define(['async!http://maps.google.com/maps/api/js?v=3&sensor=false'],
   function (gmap) {
     console.log(gmap);
   });
});

The "ready" console is logging but the define call is not triggering. If I replace it with a require call, the file is being loaded, but I gmap is undefined.

Question:
why is my define call not triggering?


Solution

  • It's because once a module is defined it needs to be required. Changing your code to something like this would work:

    // gmap.js (for example)
    define(['async!http://maps.google.com/maps/api/js?v=3&sensor=false'], function(gmap) {
        // Do some stuff
    
        return gmap;
    });
    
    // main.js
    require(['jquery', 'path/to/gmap'], function($, gmap) {
        $(function() {
            console.log(gmap);
        });
    });
    

    Some things to note: