Skip to content

Instantly share code, notes, and snippets.

@tjpeden
Created April 19, 2011 02:29
Show Gist options
  • Save tjpeden/926699 to your computer and use it in GitHub Desktop.
Save tjpeden/926699 to your computer and use it in GitHub Desktop.
CommonJS modules, loaded asynchronously, for the browser environment. A sort of POC. I donno... this is probably dumb...
jQuery(function($) {
CommonJS.require("util");
$(document).bind("require", function(e, exports) { // Probably needs a better event name
var Util = exports.Util;
Util.sing("Revelry"); // Don't ask why Util sings... it just does!
});
});
/**
* CommonJS modules, loaded asynchronously, for the browser environment.
*
* Depends on jQuery for ajax
*
* Author: TJ Peden
*/
window.CommonJS = (function() {
/**
* We create a class/object here to contain the needed functionality.
*/
function _CommonJS() {
this.exports = {}; // exports namespace
this.loading = 0; // This will help us determine when to fire event
}
_CommonJS.prototype.require = function(name) {\
this.loading++;
$.ajax({
context: this, // Makes things prettier in the success callback
dataType: 'text', // Load it as text so we can control the context it's evaluated in
url: '/javascripts/' + name + '.js', // Maybe this shouldn't be hard coded? I donno...
success: function(data) {
// Pass exports in
(new Function("exports", data))(this.exports);
this.loading--;
if(this.loading === 0) $(document).trigger("require", [this.exports]); // This probably needs some work...
}
});
};
return new _CommonJS(); // Make it a singleton... sort of?
})();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment