Skip to content

Instantly share code, notes, and snippets.

@he9lin
Created December 15, 2009 18:15
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save he9lin/257144 to your computer and use it in GitHub Desktop.
Save he9lin/257144 to your computer and use it in GitHub Desktop.
//http://bililite.com/blog/2008/08/05/namespaces-in-jquery/
(function($){
if ({}.__proto__){
// mozilla & webkit expose the prototype chain directly
$.namespace = function(name){
$.fn[name] = function namespace() { // insert this function in the prototype chain
this.__proto__ = arguments.callee;
return this;
};
$.fn[name].__proto__ = $.fn;
};
$.fn.$ = function(){
this.__proto__ = $.fn;
return this;
};
}else{
// every other browser; need to copy methods
$.namespace = function(name){
$.fn[name] = function namespace() { return this.extend(arguments.callee); };
};
$.fn.$ = function() { // slow but restores the default namespace
var len = this.length;
this.extend($.fn);
this.length = len; // $.fn has length = 0, which messes everything up
return this;
};
}
})(jQuery);
$.namespace('danny');
$.namespace('danny2');
$.fn.danny.foo = function() {return this.css('color', 'green')};
$.fn.danny2.foo = function(x){alert(x); return this; };
// now we have two different methods "foo"
$('p').danny().foo(); // colors paragraphs green
$('p').danny2().foo('Hello, world'); // alerts 'Hello, world'
$('p').danny().foo().danny2().foo('Hello, world'); // chaining works
$.fn.danny.add = function(a,b) { alert(a+b); return this;}; // defines a function with the same name as a real jQuery one
$('p').danny().add(1,2).$().add('div'); // the $() plugin restores the real jQuery namespace to a chain
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment