Skip to content

Instantly share code, notes, and snippets.

@Xiphe
Created July 28, 2015 15:17
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Xiphe/d0b2d5858a7616ad8ecd to your computer and use it in GitHub Desktop.
Save Xiphe/d0b2d5858a7616ad8ecd to your computer and use it in GitHub Desktop.
jquery-ui-like bridge for jquery plugins
/** @const */
var PLUGIN_NAME = 'myPlugin';
$.fn[PLUGIN_NAME] = function(options) {
var $els = this;
/* Method call: */
if (typeof options === 'string') {
var methodName = options;
var args = Array.prototype.slice.call(arguments, 1);
$els.each(function() {
var instance = $.data(this, 'plugin_' + PLUGIN_NAME);
if (!instance) {
throw new Error('Cannot call methods on ' + PLUGIN_NAME + ' prior to initialization; ' +
'attempted to call method "' + methodName + '".');
} else if (methodName.charAt(0) === '_' || !$.isFunction(instance[methodName])) {
throw new Error('No such method "' + methodName + '" for "' +
PLUGIN_NAME + '" instance.');
} else {
instance[methodName].apply(instance, args);
}
});
/* Instantiation: */
} else {
$els.each(function() {
var instance = $.data(this, 'plugin_' + PLUGIN_NAME);
if (instance) {
throw new Error('already instantiated "' + PLUGIN_NAME + '" on element.');
} else {
$.data(this, 'plugin_' + PLUGIN_NAME, new MyPlugin(this, options));
}
});
}
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment