Created
July 28, 2015 15:17
-
-
Save Xiphe/d0b2d5858a7616ad8ecd to your computer and use it in GitHub Desktop.
jquery-ui-like bridge for jquery plugins
This file contains hidden or 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
/** @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