Skip to content

Instantly share code, notes, and snippets.

@andrejewski
Created March 27, 2013 01:31
Show Gist options
  • Save andrejewski/5250846 to your computer and use it in GitHub Desktop.
Save andrejewski/5250846 to your computer and use it in GitHub Desktop.
Master and Slave style module handing in large Node.js applications. Depends on Underscore for its extends method, otherwise you can simply paste in your own independent extend code.
// controllerSample.js
module.exports = function($) {
return require('../slave.js')($, function($) {
/* If you need to add mixins or properties to the objects
that are given from master.js, you need to declare those
inside of this function. Otherwise, they will not work. */
_.mixin({
compactObject: function(to_clean) {
$._.map(to_clean, function(value, key, to_clean) {
if ( !!!value || (_.isString(value) && value.length === 0)) {
delete to_clean[key];
}
});
return to_clean;
}
});
// if the function is provided you mush return $ (global).
return $;
}, main);
}
function main(req, res, next) {
//...
}
// master.js
global._ = require('underscore');
global.example = require('./model/example.js')
module.exports = function($,n) {
z($,n)([
'varName: folder file',
'counter: maths counter',
'search: utils fulltext',
'etc: etc etc'
]);
}
function z($,n) {
return function(m) {
m.forEach(function(a) {
var b = a.split(': ');
var c = b[1].split(' ');
var f = $[b[0]] = require('./'+c.join('/')+'.js');
if(typeof f == 'function') {
if(f.length == 1) {
$[b[0]] = f(global);
}
}
})
n();
}
}
// slave.js
module.exports = function($, init, next) {
if(typeof next != 'function') {
global = $._.extend(global,$);
return init;
} else {
global = $._.extend(global,init($));
return next;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment