Created
March 26, 2012 17:44
-
-
Save bruth/2207399 to your computer and use it in GitHub Desktop.
Clean dynamic Python/Java package-style pattern for JavaScript modules
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// Example directory structure | |
// js/ | |
// package.js | |
// package/ | |
// mod1.js | |
// mod2.js | |
// mod3.js | |
require(['package'], function(pack) { | |
var obj1 = new pack.Mod1Class(), | |
obj2 = new pack.Mod2Class(); | |
// ... | |
}); | |
// loading individual modules still work | |
require(['package', 'package/mod3'], function(pack, mod3) { | |
var obj1 = new pack.Mod1Class(), | |
obj2 = new pack.Mod2Class(), | |
obj3 = new mod3.Mod3Class(); | |
// ... | |
}); |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# using underscore and coffeescript's splats | |
define ['underscore', 'package/mod1', 'package/mod2', 'package/mod3'], (_, modules...) -> | |
return _.extend {}, modules... |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// pure javascript | |
define(['package/mod1', 'package/mod2', 'package/mod3'], function() { | |
var i, key, module, pack = {}; | |
for (i = arguments.length; i--;) { | |
module = arguments[i]; | |
for (key in module) { | |
pack[key] = module[key]; | |
} | |
} | |
return pack; | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment