Skip to content

Instantly share code, notes, and snippets.

@gnepud
Forked from grignaak/coffee.js
Created July 5, 2012 20:25
Show Gist options
  • Save gnepud/3056230 to your computer and use it in GitHub Desktop.
Save gnepud/3056230 to your computer and use it in GitHub Desktop.
A requireJS plugin to load CoffeeScript
(function() {
var origDefine = define;
function redefine(name, definitions) {
return function (prereqs, definition) {
if (arguments.length > 2) {
throw new Error('Cannot have more than two arguments to define in ' + name);
} else if (arguments.length === 1) {
definition = prereqs;
prereqs = [];
}
definitions.push({
prereqs: prereqs,
definition: definition
});
};
}
function moduleLoader(definition, isOnlyDefinition, isLastDefinition, onLoad) {
return function () {
var result = definition;
if (typeof definition === 'function') {
result = definition.apply(this, arguments);
}
if (isOnlyDefinition) {
onLoad(result);
} else if (isLastDefinition) {
onLoad();
}
};
}
define(['coffee-script'], {
load: function (name, req, onLoad, config) {
req(['text!' + name + '.coffee'], function (text) {
var definitions = [];
var i, definition;
define = redefine(name, definitions);
try {
var node = document.createElement('script');
node.innerHTML = CoffeeScript.compile(text);
document.getElementsByTagName('head')[0].appendChild(node);
} finally {
define = origDefine;
}
if (definitions.length === 0) {
onLoad();
return;
}
for (i = 0; i < definitions.length; i++) {
definition = definitions[i];
req(definition.prereqs, moduleLoader(
definition.definition,
definitions.length === 1,
i === definitions.length - 1,
onLoad)
);
}
});
}
});
}());
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment