6

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?

2
  • 1
    LOL don't add your properties to jQuerys namespace... Commented Jan 29, 2011 at 19:13
  • 1
    Dive into RequireJS for non-jQuery plugin management ;) Commented Jan 29, 2011 at 19:34

2 Answers 2

7

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).

Sign up to request clarification or add additional context in comments.

1 Comment

Your site has been hijacked. Pages at dvt.name redirect to baaaaddd places.
4

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.