Skip to content

Instantly share code, notes, and snippets.

@atma
Created December 2, 2012 18:21
Show Gist options
  • Save atma/4190306 to your computer and use it in GitHub Desktop.
Save atma/4190306 to your computer and use it in GitHub Desktop.
jQuery plugin template
/**
* jquery.plugin.js v1.0.0
* http://github.com/someone/someplugin
*/
;( function( $, window, undefined ) {
'use strict';
var pluginName = 'pluginName',
Plugin = function( options, element ) {
this.$el = $( element );
this._init( options );
};
// the options
Plugin.defaults = {
};
Plugin.prototype = {
_init : function( options ) {
// options
this.options = $.extend( true, {}, Plugin.defaults, options );
}
};
// internal methods
var logError = function( message ) {
if ( window.console ) {
window.console.error( message );
}
};
$.fn[pluginName] = function( options ) {
var instance = $.data( this, pluginName );
if ( typeof options === 'string' ) {
var args = Array.prototype.slice.call( arguments, 1 );
this.each(function() {
if ( !instance ) {
logError( "cannot call methods on " + pluginName + " prior to initialization; " +
"attempted to call method '" + options + "'" );
return;
}
if ( !$.isFunction( instance[options] ) || options.charAt(0) === "_" ) {
logError( "no such method '" + options + "' for " + pluginName + " instance" );
return;
}
instance[ options ].apply( instance, args );
});
} else {
this.each(function() {
if ( instance ) {
instance._init();
} else {
instance = $.data( this, pluginName, new Plugin( options, this ) );
}
});
}
return instance;
};
} )( jQuery, window );
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment