Created
June 28, 2011 16:42
-
-
Save acorcutt/1051556 to your computer and use it in GitHub Desktop.
JQuery Plugin Starter
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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