All notes
Requirejs

Intro

requirejs.org.

RequireJS is a JavaScript file and module loader. It is optimized for in-browser use, but it can be used in other JavaScript environments, like Rhino and Node.

It implements the Asynchronous Module API.



<!-- ---------- main.html -->

<!-- data-main attribute tells require.js to load
     scripts/main.js after require.js loads. -->
<script data-main="scripts/main" src="scripts/require.js"></script>

<!-- ---------- main.js -->

<!-- Inside of main.js, you can use requirejs() to load any other scripts you need to run. This ensures a single entry point, since the data-main script you specify is loaded asynchronously. -->

requirejs(["helper/util"], function(util) {
    //This function is called when scripts/helper/util.js is loaded.
    //If util.js calls define(), then this function is not fired until util's dependencies have loaded, and the util argument will hold the module value for "helper/util".
});

API

define

Simple Name/Value Pairs

If the module does not have any dependencies, and it is just a collection of name/value pairs, then just pass an object literal to define():



define({
    color: "black",
    size: "unisize"
});

Example in node

requirejs.org: node.



//----- varA.js

if (typeof define !== 'function') {
  var define = require('amdefine')(module);
}

define({
  varA: 'AAA',
  varB: 'BBB'
});

//----- test.js

var varA = require('./varA');
console.log(varA);
// { varA: 'AAA', varB: 'BBB' }

Definition Functions



// Does setup work before returning its module definition.
define(function () {
    // Do setup work here
    // wcfNote: after require, the required obj is the object but not the function! That's why we say "do some setup work here", the function is run before being required.

    return {
        color: "black",
        size: "unisize"
    }
});

Definition Functions with Dependencies



define(
module_id /*optional*/, 
[dependencies] /*optional*/, 
definition function /*function for instantiating the module or object*/
);

//----- Example

define('myModule', 
  ['foo', 'bar'], 
  // module definition function dependencies (foo and bar) are mapped to function parameters
  function ( foo, bar ) {
    // return a value that defines the module export
    // (i.e the functionality we want to expose for consumption)
  
    // create your module here
    var myModule = {
      doStuff:function(){
        console.log('Yay! Stuff');
      }
    }

    return myModule;
});

//-----

var varA = require('./varA');
console.log(varA);
// { doStuff: [Function: doStuff] }