Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Best practices for JQuery namespaces + general purpose utility functions

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?

like image 223
Armchair Bronco Avatar asked Dec 28 '10 02:12

Armchair Bronco


1 Answers

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.

like image 72
Ronny Avatar answered Sep 30 '22 20:09

Ronny