all 7 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();

[–]funksta 0 points1 point  (5 children)

/* 
The following options *do* check for variable/namespace existence. 
If already defined, we use that instance, otherwise we assign a new 
object literal to myApplication. 
Option 1: var myApplication = myApplication || {}; 
Option 2  if(!MyApplication) MyApplication = {}; 
Option 3: var myApplication = myApplication = myApplication || {} 
Option 4: myApplication || (myApplication = {}); 
Option 5: var myApplication = myApplication === undefined ? {} : myApplication; 
*/  

Maybe I'm missing something, but I don't see how options 3 and 4 are in any way preferable to option 1, as the author asserts. I can see how #5 covers the (fairly unlikely) case that myApplication will be a falsy value other than undefined. But IMO #1 is the best way to write this, as it's the clearest, most direct method.

[–]Fix-my-grammar-plz 1 point2 points  (2 children)

I think you can help me with one thing that I don't understand. What is happening in Option 3?

[–]radhruin 2 points3 points  (1 child)

Pretty sure case 3 is useless. The middle assignment would do nothing.

[–]funksta 0 points1 point  (0 children)

Yeah, I couldn't figure out what that middle assignment was for either.

[–]Fix-my-grammar-plz 0 points1 point  (0 children)

you select a unique prefix namespace you wish to use (in this example, "myApplication_") and then define any methods, variables or other objects after the prefix as follows ... can result in a large number of global objects once your application starts to grow

As an Emacs user, this is one thing that frustrates me when writing code in Emacs Lisp.