Created
November 18, 2010 12:50
-
-
Save jamesbrooks/704928 to your computer and use it in GitHub Desktop.
jQuery Skeleton Plugin
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
$('#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 |
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
// 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