What are some current \"rules of thumb\" for implementing JQuery namespaces to host general purpose utility functions?
I have a number
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();
};
});
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.