atma
12/2/2012 - 6:21 PM

jQuery plugin template

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 );