PMSI-AlignAlytics/dimple — pull request #56 by stephen-james (2014-02-27 15:08:48+00:00)
Title: adding support for AMD with RequireJS

Using RequireJS to define modules that require dimple is complicated by the fact that d3 doesn't register itself in the global namespace if it detects AMD/RequireJS.

// sample from d3's end.js....

if (typeof define === "function" && define.amd) {
define(d3);
} else if (typeof module === "object" && module.exports) {
module.exports = d3;
} else {
this.d3 = d3;
}

So while it is possible to "shim" dimple using RequireJS, the d3 global reference that dimple relies on is missing (even though the d3 module is loaded).

One approach to solving this would be to wrap the entire dimple creation code in a function that serves d3 to dimple via closure. (below example code untested!)

// Wrap all application code in a self-executing function
(function () {
"use strict";

var factory = function(d3) {
// Create the stub object
var dimple = {
version: "1.1.5",
plot: {},
aggregateMethod: {}
};

// IMPLEMENTATION HERE

return dimple;
}; // end of factory

if (typeof define === "function" && define.amd) {
define(["d3"], factory);
} else if (typeof module === "object" && module.exports) {
var d3 = require("d3");
module.exports = factory(d3);
} else {
this.dimple = factory(this.d3);
}
}());
// End dimple

... but due to wrapping everything in a second level function (`factory`) all script files would have to be indented further, or we'd have to modify the grunt task to do that indentation on build. I'm also not convinced that this is most efficient.

The option presented in this pull request is a load simpler, it retrofits d3 in the global namespace if RequireJS is detected (perhaps bad for namespace pollution, but negligably?) and registers dimple both in the global namespace and as a module.

the answer to the following stack overflow question might help weigh this up....

http://stackoverflow.com/questions/17936854/when-designing-a-js-library-should-i-make-it-requirejs-amd-compatible-or-not