6

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,

Community
  • 1
  • 1
Amir
  • 349
  • 2
  • 4
  • 13
  • 1
    You don't need namespaces, just have modules with your `` – Raynos Jun 30 '11 at 16:18
  • [`requireJS`](http://requirejs.org/) defines `require` keyword to load a module and a `define` keyword to define one. You use _zero_ global scope. There are also other module loaders, go find them yourself ;) – Raynos Jun 30 '11 at 16:32

3 Answers3

20

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.

Levi Morrison
  • 19,116
  • 7
  • 65
  • 85
  • Thanks Levi for your quick response. Can you explain to me the 2nd point. jQuery doesn't have namespacing as YUI (yahoo) library. How would to organize the jQuery library without namespace/ – Amir Jun 30 '11 at 16:19
  • I understand that you can use $.fn but jQuery document mentions: "Don't clutter the jQuery.fn object with more than one namespace per plugin. " which is why i was asking what is the best way to organize libraries in jQuery? – Amir Jun 30 '11 at 16:33
  • You are correct, see http://docs.jquery.com/Plugins/Authoring#Plugin_Methods for how to namespace for your specific plugin. – Levi Morrison Jun 30 '11 at 16:35
3

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

Jeff
  • 13,943
  • 11
  • 55
  • 103
0

require.js is a better practice because it doesn't require you to add objects onto the window object unnecessarily. It also doesn't mean you have to worry about the loading order of previous javascript files.

steve
  • 1