Skip to content

Instantly share code, notes, and snippets.

@grignaak
Created March 10, 2011 23:08
Show Gist options
  • Save grignaak/865150 to your computer and use it in GitHub Desktop.
Save grignaak/865150 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)
);
}
});
}
});
}());
@grignaak
Copy link
Author

I've edited the gist to handle when no definition is given in the coffescript

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