7

What are some current "rules of thumb" for implementing JQuery namespaces to host general purpose utility functions?

I have a number of JavaScript utility methods scattered in various files that I'd like to consolidate into one (or more) namespaces. What's the best way to do this?

I'm currently looking at two different syntaxes, listed in order of preference:

  //******************************
  // JQuery Namespace syntax #1
  //******************************
  if (typeof(MyNamespace) === "undefined")
  {
     MyNamespace = {};
  }

  MyNamespace.SayHello = function ()
  {
     alert("Hello from MyNamespace!");
  }

  MyNamespace.AddEmUp = function (a, b)
  {
     return a + b;
  }

  //******************************
  // JQuery Namespace syntax #2
  //******************************
  if (typeof (MyNamespace2) === "undefined")
  {
     MyNamespace2 =
     {
        SayHello: function ()
        {
           alert("Hello from MyNamespace2!");
        },

        AddEmUp: function (a, b)
        {
           return a + b;
        }
     };
  }

Syntax #1 is more verbose but it seems like it would be easier to maintain down the road. I don't need to add commas between methods, and I can left align all my functions.

Are there other, better ways to do this?

leonheess
  • 16,068
  • 14
  • 77
  • 112
Armchair Bronco
  • 2,367
  • 4
  • 31
  • 44
  • I think the syntax #1 is better since it allows you to use the namespace in multiple files. I uses this method in my projects. – Arun P Johny Dec 28 '10 at 03:02
  • I should also extend this question to include namespaces that contain enumerations. For enums, I would still prefer syntax #1. – Armchair Bronco Dec 28 '10 at 03:26
  • NB: Placing open curly-braces on their own line is an invitation for disaster. Open-curlies should always be placed on the same line as their "owner", i.e. if(), =, etc. – Rob Raisch May 14 '11 at 22:25
  • 1
    I don't agree that open curly braces should be used according to the so-called "Indian Hill" notation where they appear at the end of lines. This is purely a stylistic thing and there is no disaster in the offing. With a decent IDE, you can have matching braces appear against a darker background color (I use light red), and having them line up along the left hand side of the page helps me immensely, especially with deeply nested code. – Armchair Bronco Jun 04 '11 at 07:07
  • @ArunPJohny: Why couldn't use a combination of the two? You could start with method 2 in a "core" file, and then in extension files use a modified version of method 1 where the declaration of the namespace is more flexible such that you could take the existing namespace and add properties and methods to it. – natlee75 Jan 12 '12 at 19:10
  • @RobRaisch: Why do you think this is such a problem? I personally keep the opening brace at the end of the line like you say, but plenty of people I've worked with use the "own line" format Armchair did. This is purely a style - there's no technical issue, but maybe that's what you meant (that it might be more difficult for others to read or make it easier for them to screw things up if they touched your code)? – natlee75 Jan 12 '12 at 19:12
  • 1
    Because of the technical issue of JS semicolon auto insertion. See http://encosia.com/in-javascript-curly-brace-placement-matters-an-example/# - if it matters in one instance, better to err on the side of caution then face difficult-to-debug errors. – Rob Raisch Jan 19 '12 at 19:51
  • Although I prefer C# style (curly braces on separate lines and PascalCase public names) it is also best to use the adopted standards for each language/technology/platform. So unfortunately when writing JavaScript that means all the stuff Java developer love and others hate :-) The other reason to follow it is any really good IDE will also warn you about style violations and auto-format back by default. I don't think it's worth the effort on every developer machine/install to go and fiddle with settings for such useful features just to go "against the grain". Maybe TypeScript can do that. – Tony Wall Oct 16 '13 at 09:18

2 Answers2

3

For jQuery plugins and such the pattern is to use $.fn.myPlugin if you want it to be available on elements, and $.whatever if you just want to use the namespace. I recommend reading the official Plugins Authoring document and these articles.

But jQuery aside, the easiest way to namespace your utils would be along these lines:

var utils = window.utils || {};
utils.method = function(){};

The basics of namespacing in JS hasn't really changed lately - You should check out snook's article, DED's elegant approach and this SO question.

The main advantage of using a self-invoked function to declare namespaces is you can execute stuff privately before returning the object. Also, the object will be ready for auto-complete by your console, which you'll miss on the $ namespace because jQuery returns a function rather than an object.

Community
  • 1
  • 1
Ronny
  • 4,295
  • 2
  • 24
  • 30
  • preferably `var utils = window.utils || {}` – Raynos May 14 '11 at 22:24
  • jQuery was probably used here as a synonym for Javascript :) At any rate, the jQuery plugin syntax does not really support namespacing (apart from `'event.namespace'` in `trigger`/`bind`); the - rather horrible - standard solution seems to be using a single function for pretty much everything. – Tgr Jun 04 '11 at 07:35
1

For the record, I ended up using the first syntax:

$(function ()
{
   //********************************
   // PREDIKT NAMESPACE
   //********************************

   if (typeof (Predikt) === "undefined")
   {
      Predikt = {};
   }

   //********************************
   // PREDIKT.TIMER NAMESPACE
   //********************************

   if (typeof (Predikt.Timer) === "undefined")
   {
      Predikt.Timer = {};
   }

   Predikt.Timer.StartTimer = function ()
   {
      return new Date().getTime();
   };

   Predikt.Timer.EndTimer = function ()
   {
      return new Date().getTime();
   };

});
Armchair Bronco
  • 2,367
  • 4
  • 31
  • 44
  • 1
    It's your call, but `Predikt = window.Predikt || {}` works great and is shorter. As long as you reference the new object as a propert (e.g. window.Predict and not just Predikt) you won't get a ReferenceError but just a new empty object. Anyway, you don't need the parens around object names. – Ronny Jun 04 '11 at 20:52