Skip to content

Instantly share code, notes, and snippets.

@jamesbrooks
Created November 18, 2010 12:50
Show Gist options
  • Save jamesbrooks/704928 to your computer and use it in GitHub Desktop.
Save jamesbrooks/704928 to your computer and use it in GitHub Desktop.
jQuery Skeleton Plugin
$('#element').plugin(); // calls init
$('#element').plugin({ foo: 'bar' }); // calls init and extends the hash into settings
$('#element').plugin('doSomething'); // calls init (if it hasn't already been done) and calls doSomething
$('#element').plugin('doSomething', { cake: 'delicious' }); // calls init and calls doSomething with the provided argument
// Rename instances of Plugin and plugin to match your plugin name.
(function($) {
$.Plugin = function(el, options) {
var base = this;
base.$el = $(el);
base.el = el;
base.$el.data('Plugin', base);
// Default settings, is extended with the hash passed when initializing.
base.settings = {
};
if (options) {
$.extend(base.settings, options);
}
// Function declarations from here on.
base.init = function() {
}
base.doSomething = function() {
// Additional function example, having 'doSomething' defined isn't required ;)
}
};
$.fn.plugin = function(method) {
var args = Array.prototype.slice.call(arguments, 1);
return this.each(function() {
var obj = $(this).data('Plugin');
if (!obj && typeof(method) === 'string') {
// Method called without init, need to init.
obj = (new $.Plugin(this));
obj.init();
}
if (obj && obj[method] && method !== 'init') {
// Standard method call.
obj[method].apply(this, args);
} else if (typeof(method) === 'object' || !method) {
// Method isn't present or is an hash for settings (init calling style), init only if needed.
if (!obj) {
obj = (new $.Plugin(this, method));
obj.init();
}
} else {
$.error('Plugin method not found: ' + method);
}
});
};
})(jQuery);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment