Skip to content

Instantly share code, notes, and snippets.

@zedd45
Created April 15, 2013 21:26
Show Gist options
  • Save zedd45/5391407 to your computer and use it in GitHub Desktop.
Save zedd45/5391407 to your computer and use it in GitHub Desktop.
jQuery plugin boilerplate
// make sure our browser supports creating new objects:
if ( typeof Object.create !== 'function' ) {
Object.create = function (o) {
function F(){}
F.prototype = o;
return new F();
};
}
/**
* create a new jQuery Plugin function for use later on.
* @param pluginNamespace - [string] - this is the namespace of the plugin that $.data() will attach to the root node of the plugin,
as well as being the name of the plugin function you'll use to create an instance
* @param pluginClass - [object literal] - this is the "class" of methods etc that comprise the plugin
* @NOTE: this is not the same as instantiating your instance.
* You MUST still call $(selector).pluginNamespace(); (with your actual plugin name)
* @NOTE: This must come after object.create is stubbed for IE8 or this plugin infrastructure will not work for that browser.
*/
myNamespace.plugin = function ( pluginNamespace, pluginClass ) {
"use strict";
jQuery.fn[ pluginNamespace ] = function( options ) {
// a sprinkle of error handling....
if ( options && "object" !== typeof options ) {
jQuery.error('options passed to ' + pluginNamespace + ' must be an object');
}
return this.each( function () {
var pluginInstance = Object.create( pluginClass );
pluginInstance.init( this, options || {} );
// save a pointer to the instance
// in the data of the DOM element it was instantiated on (this)
jQuery.data(this, pluginNamespace, pluginInstance);
});
};
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment