Last active
December 22, 2015 21:19
-
-
Save mandelbro/6532230 to your computer and use it in GitHub Desktop.
jQuery/Zepto Plugin Boilerplate
This file contains hidden or 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
/*jslint devel: true, nomen: true, unparam: true, white: true, indent: 4 */ | |
// | |
// $.fn.pluginName | |
// | |
;(function ($, window, undefined) { | |
// Give the plugin a descriptive name | |
var pluginName = 'pluginName', | |
// specify default options | |
defaults = { | |
}, | |
// The work horse, based on the factory pattern | |
// @see http://addyosmani.com/resources/essentialjsdesignpatterns/book/#factorypatternjavascript | |
Factory = function ( ) { | |
function buildEventListeners ( $element ) { | |
// add event listeners | |
} | |
function extract ( key, element, options ) { | |
var output; | |
// check if the param is even supported | |
if(defaults[key] === undefined) { | |
console.error('The "' + key + '" parameter is not supported.'); | |
return; | |
} | |
// Check the options object | |
if(output = options[key]) return output; | |
// check the element data object | |
if(output = element.data(key)) return output; | |
// return the default value | |
return defaults[key]; | |
} | |
return { | |
init : function ( $element, options ) { | |
// add element to public attributes | |
this.element = $element; | |
this.options = options || {}; | |
// add event listeners | |
buildEventListeners( this.element ); | |
return this; | |
}, | |
// extract params | |
params : function ( key ) { | |
return extract( key, this.element, this.options ) | |
} | |
// , publicVar : '' // add public vars and methods here | |
} | |
}, | |
Plugin = (function () { | |
return { | |
init : function ( $element, options ) { | |
return Factory().init( $element, options ); | |
} | |
} | |
})(); | |
// A lightweight plugin wrapper around the constructor, | |
// preventing against multiple instantiations. | |
// Also allows the caller to return the plugin module | |
// if called on a single jquery object | |
$.fn[pluginName] = function ( options ) { | |
if(this.length === 1) { | |
if(this.data('plugin_' + pluginName)) { | |
return this.data('plugin_' + pluginName); | |
} | |
return this.data('plugin_' + pluginName, Plugin.init( this, [options] )); | |
} else { | |
return this.each(function () { | |
var $this = $(this); | |
if (!$this.data('plugin_' + pluginName)) { | |
$this.data('plugin_' + pluginName, Plugin.init( $this, [options] )); | |
} | |
}); | |
} | |
}; | |
$(function () { | |
$('.js-' + pluginName)[pluginName](); | |
}); | |
})( (window.Zepto || window.jQuery), this); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment