Created
May 15, 2012 14:44
-
-
Save davist11/2702312 to your computer and use it in GitHub Desktop.
jQuery Plugin Pattern
This file contains 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
/* | |
* 'Highly configurable' mutable plugin boilerplate | |
* Author: @markdalgleish | |
* Further changes, comments: @addyosmani | |
* Licensed under the MIT license | |
*/ | |
// Note that with this pattern, as per Alex Sexton's, the plugin logic | |
// hasn't been nested in a jQuery plugin. Instead, we just use | |
// jQuery for its instantiation. | |
;(function( $, window, document, undefined ){ | |
// our plugin constructor | |
var Plugin = function( elem, options ){ | |
this.elem = elem; | |
this.$elem = $(elem); | |
this.options = options; | |
// This next line takes advantage of HTML5 data attributes | |
// to support customization of the plugin on a per-element | |
// basis. For example, | |
// <div class=item' data-plugin-options='{"message":"Goodbye World!"}'></div> | |
this.metadata = this.$elem.data( 'plugin-options' ); | |
}; | |
// the plugin prototype | |
Plugin.prototype = { | |
defaults: { | |
message: 'Hello world!' | |
}, | |
init: function() { | |
// Introduce defaults that can be extended either | |
// globally or using an object literal. | |
this.config = $.extend({}, this.defaults, this.options, | |
this.metadata); | |
// Sample usage: | |
// Set the message per instance: | |
// $('#elem').plugin({ message: 'Goodbye World!'}); | |
// or | |
// var p = new Plugin(document.getElementById('elem'), | |
// { message: 'Goodbye World!'}).init() | |
// or, set the global default message: | |
// Plugin.defaults.message = 'Goodbye World!' | |
this.sampleMethod(); | |
return this; | |
}, | |
sampleMethod: function() { | |
// eg. show the currently configured message | |
// console.log(this.config.message); | |
} | |
} | |
Plugin.defaults = Plugin.prototype.defaults; | |
$.fn[pluginName] = function ( options ) { | |
return this.each(function () { | |
if (!$.data(this, 'plugin_' + pluginName)) { | |
$.data(this, 'plugin_' + pluginName, new Plugin( this, options )); | |
} | |
}); | |
}; | |
//optional: window.Plugin = Plugin; | |
})( jQuery, window , document ); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment