Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is JQuery namespace a good practice?

Can anyone explain to me please that if using a namespace is a good coding practice. And why is it needed? If it was a good approach why JQuery didn't include it by default. There is a separate plugin to allow this functionality.

I saw this post that mentions few ways to do it. Someone mentioned about memory leak in the post that is worrisome.

Lastly, what is the best way to organize JQuery libraries?

thanks,

like image 344
Amir Avatar asked Jun 30 '11 16:06

Amir


2 Answers

Notes:

  • Namespacing is a good practice because you have less chance of having conflicting names with other scripts. This way, only your name-space has to be unique, but multiple name-spaces can have the same functions in them.
  • jQuery DOES use namespacing, and you do not need the plug-in. The jQuery object itself is a name-space. . . Any function inside jQuery is 'name-spaced' in the jQuery object. This is true for any JavaScript object.

In response to Amir's comment:

YUI achieves namespacing by adding a variable to the YUI object where the added variable is also an object. Their namespace function just builds it for you.

var lib = {
    util:{},
    widget:{},
    tool:{}
};

//creates a function named reset in the lib.util namespace
lib.util.reset = function() {};

//creates a function named reset in the lib.widget namespace
lib.widget.reset = function() {};

In jQuery, you add it to the jQuery.fn (or $.fn if you use $ for jQuery() namespace.

like image 88
Levi Morrison Avatar answered Oct 05 '22 14:10

Levi Morrison


Re: best ways to organize jQuery libraries, you should start by reading the Plugins Authoring article on jquery.com:

http://docs.jquery.com/Plugins/Authoring

like image 26
Jeff Avatar answered Oct 05 '22 13:10

Jeff