Guest User

Untitled

a guest
Jun 2nd, 2012
29
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.23 KB | None | 0 0
  1. // top-level namespace being assigned an object literal
  2. var myApp = myApp || {};
  3. // a convenience function for parsing string namespaces and
  4. // automatically generating nested namespaces
  5. function extend( ns, ns_string ) {
  6. var parts = ns_string.split('.'),
  7. parent = ns,
  8. pl, i;
  9. if (parts[0] == "myApp") {
  10. parts = parts.slice(1);
  11. }
  12. pl = parts.length;
  13. for (i = 0; i < pl; i++) {
  14. //create a property if it doesnt exist
  15. if (typeof parent[parts[i]] == 'undefined') {
  16. parent[parts[i]] = {};
  17. }
  18. parent = parent[parts[i]];
  19. }
  20. return parent;
  21. }
  22. // sample usage:
  23. // extend myApp with a deeply nested namespace
  24. var mod = extend(myApp, 'myApp.modules.module2');
  25. // the correct object with nested depths is output
  26. console.log(mod);
  27. // minor test to check the instance of mod can also
  28. // be used outside of the myApp namesapce as a clone
  29. // that includes the extensions
  30. console.log(mod == myApp.modules.module2); //true
  31. // further demonstration of easier nested namespace
  32. // assignment using extend
  33. extend(myApp, 'moduleA.moduleB.moduleC.moduleD');
  34. extend(myApp, 'longer.version.looks.like.this');
  35. console.log(myApp);
Advertisement
Add Comment
Please, Sign In to add comment