문제

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?

도움이 되었습니까?

해결책

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:

  • Modules that are defined should live in individual files. Read this page in the API documentation to grasp how they work.
  • Avoid requiring modules inside a DOM ready callback, this means you have to wait longer before the modules can be requested. Better to start requesting them straight away and check for DOM readiness later. RequireJS comes with a DOM ready plugin just for this.
  • Ensure you require jQuery as a module (unless you aren't using it as such).
  • Passing an anonymous function to $() is a shortcut for $(document).ready()
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top