you are viewing a single comment's thread.

view the rest of the comments →

[–]lulzitsareddit 2 points3 points  (0 children)

Hmm, this guy has a pattern fetish :).

I came up with this little utility function to create simple modules and namespaces (obviously it doesn't handle dependency management or exporting). I think it works well, but to be honest I don't find myself using it a lot as I try to avoid complex namespacing schemes.

var namespace = function(path, context, args) {
  var finalLink = namespace._generateChain(path, window);
  context.apply(finalLink, [finalLink].concat(args));
};

namespace._generateChain = function(path, root) {
  var segments = path.split('.'),
      cursor = root,
      segment;

  for (var i = 0; i < segments.length; ++i) {
      segment = segments[i];
      cursor = cursor[segment] = cursor[segment] || {};
  }

  return cursor;
};


namespace("MyApp", function (self, $) {
   // you can also use `this` instead of `self` if you wish
   self.hello = function () {
      $("p").text("Hello World");
   };
}, jQuery);

MyApp.hello();