incubator-callback-dev mailing list archives

Site index · List index
Message view « Date » · « Thread »
Top « Date » · « Thread »
From James Burke <jrbu...@gmail.com>
Subject Re: CommonJS and AMD (and, not or)
Date Tue, 13 Dec 2011 19:56:16 GMT
On Tue, Dec 13, 2011 at 11:25 AM, Brian LeRoux <b@brian.io> wrote:
> Looks rad. I'm curious what an AMD plugin vs the same plugin authored
> in CJS style would look like. Just a hello world.

Usually the only difference for coding a callback plugin in AMD or CJS
would be a define wrapper in the AMD case:

define(function(require, exports, module){
    //CJS stuff goes in here.
    var PG = require('phonegap');

    //to export a module value
    module.exports = {};
});

Most of the time, exports and module is not needed when using AMD, so
you can just do:

define(function(require){
    var PG = require('phonegap');

    //to set the module exports, return a value.
    //can be a function.
    return {};
});

AMD's define allows for imperative require use with a callback, so:

define(function(require){
    var mod = someCondition ? 'a' : 'b';

    require([mod], function (modExports) {
        //called back asynchronously.
    });
});

This is really helpful for something like google maps code, where you
may not want to load the code right away, but in response to a user
action. This is difficult to express in CommonJS code, since require
is always synchronous in that environment.

Note though, that to get the dynamic require support for loading
network resources a dynamic require loader, like RequireJS, curl,
dojo, would be needed instead of almond. However, if the module was
built into the built file containing almond, the above callback-style
require will work with almond.

James

Mime
View raw message