Skip to content

Instantly share code, notes, and snippets.

@frne
Created December 22, 2011 10:17
Show Gist options
  • Save frne/1509818 to your computer and use it in GitHub Desktop.
Save frne/1509818 to your computer and use it in GitHub Desktop.
jQuery plugin pattern
/**
* jQuery plugin pattern
*
* An example or pattern for jQuery plugin authoring
*
*/
( function ( $ ) {
/**
* Use the following vars to define your function
*
* Sample call: "jQuery.%pluginName%( "%method%", args );"
*/
// the function name of the plugin
var pluginName = "myPlugin",
// the used methods
methods = {
/**
* Initializing function
*
* This function will be called, if no method is set in params
* Example: jQuery.myPlugin( { foo: 'bar' };" or jQuery.myPlugin( false, { foo: 'bar' } );"
*
* @param options mixed All Parameters given to the jQuery as Array or Object
*/
init:function ( options ) {
console.info( "init" );
console.log( options );
alert("Usage: jQuery()." + pluginName + "('method',{foo: 123, bar: 'baz'});");
},
/**
* Initializing function
*
* This function will be called, if no method is set in params
* Example: jQuery.myPlugin( { foo: 'bar' };" or jQuery.myPlugin( false, { foo: 'bar' } );"
*
* @param options mixed All Parameters given to the jQuery as Array or Object
*/
show:function ( options ) {
console.info( "show" );
console.log( options );
},
hide:function () {
console.info( arguments );
console.info( this );
return this;
}
};
/**
* jQuery plugin registration and method call logic
*
* Usually you don't have to change this.
*/
$.fn[ pluginName ] = function ( method ) {
// get the target
var $this = $( this );
// Method logic
if ( typeof methods[ method ] === "function" ) {
return methods[ method ].apply( $this, Array.prototype.slice.call( arguments, 1 ) ) || $this;
} else if ( typeof method === 'object' || !method ) {
return methods.init.apply( $this, arguments ) || $this;
} else {
$.error( "Method " + method + " does not exist on jQuery." + pluginName );
// return always $this, becuase of fluent usage
return $this;
}
};
})( jQuery );
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment