Skip to content

Instantly share code, notes, and snippets.

@hongymagic
Created February 13, 2012 01:57
Show Gist options
  • Save hongymagic/1812720 to your computer and use it in GitHub Desktop.
Save hongymagic/1812720 to your computer and use it in GitHub Desktop.
Simple CommonJS module implementation
'use strict';
/**
* Simple module define/require functionality
*
* NOTE: this is NOT requirejs
*/
var modules = {};
/**
* Require
*
* var grid = require('UI.views.grid');
*/
function require(name) {
var
ns = String.prototype.split.call(name, '.'),
name,
module = modules;
while (name = Array.prototype.shift.call(ns)) {
module = module[name];
if (typeof module == 'undefined') {
throw TypeError('module: ' + name + ' could not be found');
}
}
return module;
}
/**
* Define
*
* require.define('UI.views', function (module, exports, require) {
* exports.grid = function () {};
* });
*/
(function (require) {
var
copy = function (target, source, overwrite) {
var key;
for (key in source) {
if (overwrite || target[key] === undefined) {
target[key] = source[key];
}
}
return target;
},
create = function (namespace, value) {
var node = modules,
ns = namespace ? String.prototype.split.call(namespace, '.') : [],
name = null,
nso;
while (name = Array.prototype.shift.call(ns)) {
nso = node[name];
if (!nso) {
nso = (value && ns.length === 0) ? value : {};
node[name] = nso;
}
node = nso;
}
return node;
};
require.define = function (rs, fn, overwrite) {
var
module = {},
exports = {},
ns = String.prototype.split.call(rs, '.'),
node = modules,
nso;
module.exports = exports;
fn(module, exports, require);
copy(create(rs), module.exports, overwrite);
};
}(require));
// The idea is to keep extending like partials in C# instead of replacing namespace
require.define('ui.views', function (module, exports, require) {
var models = require('models');
exports.GridView = function () {
this.model = models.Grid;
};
});
require.define('ui.views', function (module, exports, require) {
exports.CellView = function () {};
});
var views = require('ui.views');
var grid = new views.GridView;
var cell = new views.CellView;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment