Skip to content

Instantly share code, notes, and snippets.

@rendfall
Created July 18, 2014 11:52
Show Gist options
  • Save rendfall/570431ded594d683a90a to your computer and use it in GitHub Desktop.
Save rendfall/570431ded594d683a90a to your computer and use it in GitHub Desktop.
JS Plugin example
(function ($) {
$.fn.PluginExample = function(param) {
function PluginExampleClass()
{
/* -------------------------------------------------------------- */
/* public: */
this.api = {
methodExample : function(i) { methodExample(i); return this.api; },
}
this.init = function(o, param)
{
if ($this) {
throw 'ERROR: Already inited.';
return;
}
$this = o;
if (typeof param === 'object')
$.extend(settings, param);
init();
}
/* -------------------------------------------------------------- */
/* private: */
var $this = null;
var settings = {
param1 : 'something',
};
var $handler;
var size = null;
var position = null;
function setupEvents(){}
function methodExample(i){}
function init(){
setupEvents();
}
}
/* ------------------------------------------------------------------ */
var pluginData;
var pluginDataName = 'PluginExample';
if (typeof param === 'string' && param == "api") {
if (this.size()==1) {
pluginData = this.data(pluginDataName);
if (pluginData)
return pluginData.api; else
throw 'ERROR: There is no API. Try to call $(_selector_).' + pluginDataName + '() first.';
} else {
throw 'ERROR: API can be fetched only for one jQuery object. Selector points to ' + this.size() + ' elements.';
}
}
return this.each(function() {
pluginData = $(this).data(pluginDataName);
if (!pluginData) {
pluginData = new PluginExampleClass();
pluginData.init($(this), param);
$(this).data(pluginDataName, pluginData);
} else {
throw 'ERROR: Already inited.';
}
});
};
})(jQuery);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment