Skip to content

Instantly share code, notes, and snippets.

@shaneriley
Created October 12, 2012 14:16
Show Gist options
  • Save shaneriley/3879386 to your computer and use it in GitHub Desktop.
Save shaneriley/3879386 to your computer and use it in GitHub Desktop.
jQuery.createPlugin
// Use: passing in an object representing a jQuery plugin. The object is expected to have
// a name attribute (your plugin name in string form, e.g. name: "accordion") and an init
// method. The createPlugin method will take each element in the collection when the
// plugin method is called and initialize the plugin individually, writing a data object
// to the element with the same name as the plugin and storing the plugin object for
// later reference.
(function($) {
$.createPlugin = function(plugin) {
$.fn[plugin.name] = function(opts) {
var $els = this,
method = $.isPlainObject(opts) || !opts ? "" : opts;
if (method && plugin[method]) {
plugin[method].apply($els, Array.prototype.slice.call(arguments, 1));
}
else if (!method) {
$els.each(function(i) {
var plugin_instance = $.extend(true, {
$el: $els.eq(i)
}, plugin, opts);
$els.eq(i).data(plugin.name, plugin_instance);
plugin_instance.init();
});
}
else {
$.error('Method ' + method + ' does not exist on jQuery.' + plugin.name);
}
return $els;
};
};
})(jQuery);
(function($) {
var accordion = {
name: "accordion",
init: function() {
if (this.$el.data(this.name)) { return; }
// Run event listeners, setup code, etc. here
}
};
$.createPlugin(accordion);
})(jQuery);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment