Skip to content

Instantly share code, notes, and snippets.

@maestrow
Last active August 29, 2015 14:04
Show Gist options
  • Save maestrow/9c9fced15d24021dd495 to your computer and use it in GitHub Desktop.
Save maestrow/9c9fced15d24021dd495 to your computer and use it in GitHub Desktop.
Requirejs Cheat Sheet

http://requirejs.org/docs/api.html

Configuration

Project structure:

  • www/
    • index.html
    • js/
      • app/
        • sub.js
      • lib/
        • jquery.js
        • canvas.js
      • app.js

in index.html: <script data-main="js/app.js" src="js/require.js"></script>

and in app.js:

requirejs.config({
  //By default load any module IDs from js/lib
  baseUrl: 'js/lib', 
  //except, if the module ID starts with "app",
  paths: {
    app: '../app'  // relative to baseUrl
  },
  // only use shim config for non-AMD scripts
  shim: {
    'backbone': {
      deps: ['underscore', 'jquery'],
      //Once loaded, use the global 'Backbone' as the module value.
      exports: 'Backbone'
    }
  }
});

// Start the main app logic.
requirejs(['jquery', 'canvas', 'app/sub'],
function   ($,        canvas,   sub) {
    //jQuery, canvas and the app/sub module are all
    //loaded and can be used here now.
});

Define a module

my/shirt.js

If module is just a collection of name/value pairs:

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

If need to do a setup work:

define(function () {
    //Do setup work here

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

With dependencies:

//module in the same directory as shirt.js
define(["./cart", "./inventory"], function(cart, inventory) {
    //return an object to define the "my/shirt" module.
    return {
        color: "blue",
        size: "large",
        addToCart: function() {
            inventory.decrement(this);
            cart.add(this);
        }
    }
});

// require
define(function (require) {
    var EntryPoint = require("./EntryPoint");
    var Model1 = require("./Model1");
    var Model2 = require("./Model2");
    var Helper = require("./Helper");

    var entryPoint = new EntryPoint(new Model1(), new Model2(new Helper()));
    entryPoint.start();
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment