Skip to content

Instantly share code, notes, and snippets.

@erfanio
Last active January 21, 2016 19:45
Show Gist options
  • Save erfanio/8ed278f6a61385a6c447 to your computer and use it in GitHub Desktop.
Save erfanio/8ed278f6a61385a6c447 to your computer and use it in GitHub Desktop.
jquery plugin template
// the semi-colon before function invocation is a safety net against concatenated
// scripts and/or other plugins which may not be closed properly.
;(function ($) {
var privateMethod = function () {
// ...
};
var Plugin = function (element, options) {
// `this` refers to a `Plugin` intance
this.element = element;
this.options = {
// default options
};
/*
* Initialization
*
*
* `this` inside a jquery function refers to a DOM element
* this.element.fadeIn('normal', function(){
* `this` keyword is a DOM element
* });
*/
this.init(options);
};
Plugin.prototype = {
// initialize options
init: function (options) {
// Merge new options with old options
$.extend(this.options, options);
/*
* Update plugin for options
*/
},
publicMethod: function () {
// ...
}
};
/*
* Plugin wrapper, preventing against multiple instantiations and
* return plugin instance.
*/
$.fn.pluginName = function (options) {
// `this` is a jquery object
// $(this) == $($('selector'))
var plugin = this.data('datakey');
// has plugin instantiated ?
if (plugin instanceof Plugin) {
// if have options arguments, call plugin.init() again
if (typeof options !== 'undefined') {
plugin.init(options);
}
} else {
// `new` calls Plugin as a constructor
plugin = new Plugin(this, options);
this.data('datakey', plugin);
}
return plugin;
};
}(jQuery));
/*
If you need independent Plugin instance per element
$('selector').each(function () {
$(this).pluginName();
});
*/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment