Skip to content

Instantly share code, notes, and snippets.

@ThisIsMissEm
Created April 7, 2011 01:34
Show Gist options
  • Save ThisIsMissEm/906880 to your computer and use it in GitHub Desktop.
Save ThisIsMissEm/906880 to your computer and use it in GitHub Desktop.

Currently the AMD syntax requires a large amount of repetition just to always get access to our required modules, this could be simplified by doing the following:

/**
 * Defines a new module
 *
 * @param {String} name         An optional name for the module || filename.
 * @param {Array}  dependencies Dependencies for the module, can be omitted.
 * @param {Function|Object} module The Modules code.
**/
define([name,] [dependencies,] module);

I propose that the signature of the module argument be changed such that if module is a function, then the signature is:

function(dep1, dep2, dep3, dep4)

The changes here are that I've removed the require and exports members, instead, you would attach methods to the this variable. Example:

define('alpha', ['beta', 'gamma'], function(beta, gamma) {
  this.verb = function() {
    return beta.foo;
  }
});

Essentially, if you're needing to call require() then you should really be defining that as a module dependency.

Likewise for object literal definitions:

define('alpha', ['beta', 'gamma'], {
  verb: function() {
    return this.dependencies.beta.foo;
  }
});
@unscriptable
Copy link

The third code snippet you show will work in the current AMD loaders (RequireJS, bdLoad, and curl.js at least) since they're all CommonJS Modules 1.1 compliant and node.js compliant. Specifically, this = exports in node.js. The last example you show is interesting. :)

@ThisIsMissEm
Copy link
Author

Actually it won't, as the signature is missing the exports and require variables.

define('alpha', ['beta', 'gamma'], function(require, exports, beta, gamma) {
  // ...
});

vs.

define('alpha', ['beta', 'gamma'], function(beta, gamma) {
  // ...
});

@jrburke
Copy link

jrburke commented Apr 7, 2011

Using "this" is hazardous: once your module needs to use another module's callback-based API, it is better to use exports or your own variable, to avoid incorrectly-bound "this" errors in the callback. Also, I find return to be much better for definition than binding individual properties to exports:

define('alpha', ['beta', 'gamma'], function (beta, gamma) {
    var alpha = {
        verb: function () {}
    };
    return alpha;
});

The "this.dependencies.beta" approach is also more typing than just using the function wrapper, and with the function wrapper/local variable for beta, it minifies better.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment