Skip to content

Instantly share code, notes, and snippets.

@chrisdickinson
Created July 10, 2010 20:00
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save chrisdickinson/470980 to your computer and use it in GitHub Desktop.
Save chrisdickinson/470980 to your computer and use it in GitHub Desktop.
interop between browser js and commonjs
<script type="text/javascript" src="namespace.js"></script>
<script type="text/javascript" src="example.module.js"></script>
<script type="text/javascript">
console.log(example.module.test_fn("hello", "world"));
</script>
var module = require('./example.module'),
sys = require('sys');
sys.puts(module.test_fn('hello', 'world'));
var get_global_object, exp=null;
try {
exp = exports;
get_global_object = require('./namespace').get_global_object;
} catch(Error) {}
(function(global) {
var exporter = global.getExporter('module');
var test_fn = function() {
return arguments;
};
exporter('test_fn', test_fn);
})(get_global_object('example', exp);
function documentNamespace(namespace) {
return {
'require':function(what) {
var split = what.split('.'),
retval = window;
for(var i = 0, len = split.length; i < len; ++i) {
retval = retval[split[i]];
}
return retval;
},
'getExporter':function(name) {
window[namespace][name] = (window[namespace][name] === undefined) ? {} : window[namespace][name];
return function(export_name, to_export) {
window[namespace][name][export_name] = to_export;
};
},
}
}
function commonjsNamespace(exp) {
exp['require'] = function(what) {
return require(['./',what].join(''));
};
exp['getExporter'] = function(name) {
var self = this;
return function(export_name, to_export) {
self[export_name] = to_export;
};
};
return exp;
}
function get_global_object(namespace, exp) {
if(exp) {
return commonjsNamespace(exp);
}
if(window[namespace]) {
return window[namespace];
} else {
window[namespace] = documentNamespace(namespace);
return window[namespace];
}
}
try {
exports.get_global_object = get_global_object;
} catch(Error) {}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment