Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JavaScript Namespace with jQuery

How do you manage namespace for a custom JavaScript library depends on jQuery?

Do you create your own namespace, say foo and add your objects there? e.g. foo.myClass, foo.myFunction

Or do you add your objects to jQuery's namespace? e.g. jQuery.myClass, jQuery.myFunction

Which is the more common practice and why?

like image 999
Tom Tucker Avatar asked Jan 29 '11 19:01

Tom Tucker


People also ask

What is namespace in JavaScript and how it is used?

JavaScript Namespaces: Namespace refers to the programming paradigm of providing scope to the identifiers (names of types, functions, variables, etc) to prevent collisions between them. For instance, the same variable name might be required in a program in different contexts.


2 Answers

This article discusses writing jQuery plugins/libraries in excruciating detail.

What NOT to do:

(function( $ ){

  $.fn.tooltip = function( options ) { // THIS };
  $.fn.tooltipShow = function( ) { // IS   };
  $.fn.tooltipHide = function( ) { // BAD  };
  $.fn.tooltipUpdate = function( content ) { // !!!  };

})( jQuery );

What to do:

(function( $ ){

  var methods = {
    init : function( options ) { // THIS },
    show : function( ) { // IS   },
    hide : function( ) { // GOOD },
    update : function( content ) { // !!! }
  };

  $.fn.tooltip = function( method ) {

    // Method calling logic
    if ( methods[method] ) {
      return methods[ method ].apply( this, Array.prototype.slice.call( arguments, 1 ));
    } else if ( typeof method === 'object' || ! method ) {
      return methods.init.apply( this, arguments );
    } else {
      $.error( 'Method ' +  method + ' does not exist on jQuery.tooltip' );
    }    

  };

})( jQuery );

I also wrote a blog post last year about various methods for namespacing in JavaScript (non-jQuery related).

like image 139
David Titarenco Avatar answered Sep 20 '22 06:09

David Titarenco


It would depend on what the library does.

  • If you're extending the functionality of instances of jQuery objects, you'd use jQuery.fn as was described very nicely by @David Titarenco in his answer.

  • If you're creating utilities that are meant to be seen as additions to those provided in window.jQuery, then I don't see a problem with using that namespace (as long as you're careful with naming).

  • If it is really its own separate library that is not meant to be seen as an extension of jQuery, yet relies on functionality from jQuery, then definitely use your own namespace.

like image 43
user113716 Avatar answered Sep 20 '22 06:09

user113716