Last active
August 29, 2015 14:19
-
-
Save baniol/305ed3dc982e063f4dac to your computer and use it in GitHub Desktop.
Function for namexpacing modules, from: http://addyosmani.com/blog/essential-js-namespacing/
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
// top-level namespace being assigned an object literal | |
var myApp = myApp || {}; | |
// a convenience function for parsing string namespaces and | |
// automatically generating nested namespaces | |
function extend( ns, ns_string ) { | |
var parts = ns_string.split('.'), | |
parent = ns, | |
pl, i; | |
if (parts[0] == "myApp") { | |
parts = parts.slice(1); | |
} | |
pl = parts.length; | |
for (i = 0; i < pl; i++) { | |
//create a property if it doesnt exist | |
if (typeof parent[parts[i]] == 'undefined') { | |
parent[parts[i]] = {}; | |
} | |
parent = parent[parts[i]]; | |
} | |
return parent; | |
} | |
// sample usage: | |
// extend myApp with a deeply nested namespace | |
var mod = extend(myApp, 'myApp.modules.module2'); | |
// the correct object with nested depths is output | |
console.log(mod); | |
// minor test to check the instance of mod can also | |
// be used outside of the myApp namesapce as a clone | |
// that includes the extensions | |
console.log(mod == myApp.modules.module2); //true | |
// further demonstration of easier nested namespace | |
// assignment using extend | |
extend(myApp, 'moduleA.moduleB.moduleC.moduleD'); | |
extend(myApp, 'longer.version.looks.like.this'); | |
console.log(myApp); |
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
var namespace = (function () { | |
// defined within the local scope | |
var privateMethod1 = function () { /* ... */ } | |
var privateMethod2 = function () { /* ... */ } | |
var privateProperty1 = 'foobar'; | |
return { | |
// the object literal returned here can have as many | |
// nested depths as you wish, however as mentioned, | |
// this way of doing things works best for smaller, | |
// limited-scope applications in my personal opinion | |
publicMethod1: privateMethod1, | |
//nested namespace with public properties | |
properties:{ | |
publicProperty1: privateProperty1 | |
}, | |
//another tested namespace | |
utils:{ | |
publicMethod2: privateMethod2 | |
} | |
... | |
} | |
})(); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment