JavaScript AMD Example with RequireJS

One line of code is worth ten thousand words.

./index.html

<!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8" />
    <title>Asynchronous Module Definition Example with RequireJS</title>
  </head>
  <body>  
    <!-- Let's use RequireJS as module loader (there are also others!) -->
    <script src="./js/require-1.0.4.js"></script>
    <script>
      require(['js/my_amd_module'], // Requires ./js/my_amd_module.js
      function(myModule)
      {
        myModule.sayHello();
        myModule.doSomething();        
      });
    </script>
</html>

./js/my_amd_module.js

define('js/my_amd_module', // module name, has to match filename (without .js)
  ['js/jquery-1.7.min'], // requirements of this module (./js/jquery-1.7.min.js)
  function($) // $ for jQuery
  {
    return {
      sayHello: function()
      {
        alert('Hello World!');
      },
      doSomething: function()
      {
        alert('I did.');
      }
    };
  });

Schreibe einen Kommentar

Deine E-Mail-Adresse wird nicht veröffentlicht. Erforderliche Felder sind mit * markiert

Diese Website verwendet Akismet, um Spam zu reduzieren. Erfahre mehr darüber, wie deine Kommentardaten verarbeitet werden.