My jQuery Plugin Development Notes
by amindunited
HTML
<h1>Since the new jQuery plugin development notes suck, and the good ones have been removed:</h1>
<div>PS:<a href="http://extraordinarythoughts.com/2011/08/20/understanding-jquery-plugins/">This post covers all of this stuff even better</a>
<ol>
<li>
<div class="description">The function should be wrapped and passed the '$'</div>
<pre>
(function ($){
}(jQuery));
</pre>
</li>
<li>
<div class="description">Plugins with often have properties, and functions so we create seporate objects for them</div>
<pre>
(function ($){
//An object to hold the default values
var defaults = {};
//An object to hold the functions of the plugin
var methods = {};
//The plugin function
$.fn.myPlugin = function(){
return this;
}
}(jQuery));
</pre>
</li>
<li>
<div class="description">Handle Multiple elements</div>
<pre>
(function ($){
//An object to hold the default values
var defaults = {};
//An object to hold the functions of the plugin
var methods = {};
//The plugin function
$.fn.myPlugin = function(){
//Handle many objects indavidually:
return this.each(function(){
//Now $this, anywhere in the plugin,
//will refer to the current obj of this each statement
var $this = $(this);
});
}
}(jQuery));
</pre>
</li>
<li>
<div class="description">Calling Methods and Using Multiple elements inside the Methods</div>
<pre>
(function ($){
//An object to hold the default values
var defaults = {};
//An object to hold the functions of the plugin
var methods = {
//Handle many objects indavidually:
init: function(){
return this.each(function(){
var $this = $(this);
});
},
//Handle many objects indavidually:
destroy:...
JavaScript
(function ($){
//An object to hold the default values
var defaults = {};
//An Object to hold the combined defaults and user defined options
var settings = {};
//An object to hold the functions of the plugin
var methods = {
//Handle many objects indavidually:
init: function(){
return this.each(function(){
var $this = $(this);
});
},
//Handle many objects indavidually:
destroy: function(){
return this.each(function(){
var $this = $(this);
});
}
};
//The plugin function
$.fn.myPlugin = function(options){
//merge the options, and the defaults into the settings
//this could also be done in each Method
settings = $.extend({}, defaults, options);
//Add the settings to each element:
$(this).each(function(){
$(this).data('myPlugin', settings);
})
var method = arguments[0];
//test if the first argument is a method
if(methods[method]) {
method = methods[method];
//if a method was passed, we remove it from the arguments, and pass the remaining arguments
arguments = Array.prototype.slice.call(arguments, 1);
} else if( typeof(method) == 'object' || !method ) {
method = methods.init;
} else {
$.error( 'Method ' + method + ' does not exist on jQuery.pluginName' );
return this;
}
// Use apply to send arguments when calling our selected method
return method.apply(this, arguments);
}
}(jQuery));