Skip to content

Instantly share code, notes, and snippets.

@acorcutt
Created June 28, 2011 16:42
Show Gist options
  • Save acorcutt/1051556 to your computer and use it in GitHub Desktop.
Save acorcutt/1051556 to your computer and use it in GitHub Desktop.
JQuery Plugin Starter
// JQuery Plugin Starter
// ----------------------------------------------------
// Setup a namespace we can use for data, events etc.
// Wraps methods internally with support for arguments.
//
// $('div').myplugin(); //call init
// $('div').myplugin({color:'green'}).fadeIn(); //init with options and chained
// $('div').myplugin('destroy'); //custom method
// $('div').myplugin('custom',10,2); //custom method with arguments
//
(function($){
var namespace = "myplugin";
var methods = {
init : function( options ){
var settings = {color:'blue'};
if(options){$.extend( settings, options );}
//do something maintaining the chain
return this.each(function(){
$(this).css('background',settings.color);
});
},
destroy : function(){
//another method returning a value
return true;
},
custom : function(a,b){
//another method with arguments returning a value
return a+b;
}
};
var plugin = new Object();
plugin[namespace]=function(method){
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.'+namespace);
}
};
$.fn.extend(plugin);
})(this.jQuery);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment