Created
July 22, 2011 23:03
-
-
Save ashrewdmint/1100638 to your computer and use it in GitHub Desktop.
Package.js
This file contains 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
// Package.js | |
// by Andrew Smith [[email protected]] | |
// Package.create("pages/signup", function(){ | |
// | |
// // You can load dependencies--nothing will be loaded twice! | |
// Package.load("plugins/something"); | |
// | |
// // Put your code here! | |
// // Remember, variables you define here must be global if you | |
// // want other packages to be able to access them. I recommend | |
// // attaching desired global variables to `window` to make them | |
// // appear explicitly global--that way there is no confusion. | |
// | |
// }); | |
// | |
// Package.load("pages/signup"); <-- loads signup code | |
// Package.load("pages"); <-- loads all pages | |
// Package.load("one two three"); <-- load multiple things | |
window._packages = { | |
_loaded: {} | |
}; | |
var Package = { | |
create: function(path, code) { | |
this.pathfinder(path, code); | |
}, | |
load: function(path) { | |
if (path.indexOf(' ') >= 0) { | |
var paths = path.split(' '); | |
for (var i=0; i<paths.length; i++) { | |
this.load(paths[i]); | |
} | |
return; | |
} | |
var code = this.pathfinder(path); | |
// Only load this if it hasn't been loaded before | |
if (! window._packages._loaded[path]) { | |
if (typeof(code) == 'function') { | |
code(); | |
} | |
// Attempt to load everything in this object | |
else if (typeof(code) == 'object') { | |
for (var x in code) { | |
if (typeof(x) == 'string') { | |
if (x != "_loaded") this.load(path + "/" + x); | |
} | |
} | |
} else { | |
throw("Package: couldn't load `" + path + "` because there's no code there!"); | |
} | |
window._packages._loaded[path] = true; | |
} | |
}, | |
pathfinder: function(path, value) { | |
path = path.replace(/\/{2,}/g, "/").split('/'); // Replace multiple slashes with one slash | |
var base = window._packages; | |
var last = base; | |
if (path[0] == "_loaded") throw("Package: _loaded is reserved, please use something else"); | |
// Iterate through each path segment | |
for (var i=0; i<path.length; i++) { | |
var segment = path[i]; | |
// If we're at the last segment | |
if (i + 1 == path.length) { | |
// Return the result or set it with the value | |
if (value == undefined) { | |
return last[segment]; | |
} else { | |
last[segment] = value; | |
} | |
} else { | |
// Make the segment an object if it isn't already | |
if (typeof(last[segment]) != 'object') { | |
last = last[segment] = {}; | |
} else { | |
last = last[segment]; | |
} | |
} | |
} | |
return window._packages = base; | |
} | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment