Plugins Summary
Key plugin patterns: extend $.fn, return this.each(), accept options with $.extend, namespace events, store instances with .data(), provide a destroy method.
Key plugin patterns: extend $.fn, return this.each(), accept options with $.extend, namespace events, store instances with .data(), provide a destroy method.
;(function($) {
$.fn.myPlugin = function(options) {
const defaults = { /* ... */ };
const settings = $.extend({}, defaults, options);
return this.each(function() {
if ($(this).data("myPlugin")) return; // no double init
const instance = { settings, el: this };
$(this).data("myPlugin", instance);
// Setup events with namespace
$(this).on("click.myPlugin", handler);
});
};
}(jQuery));
Save this template and use it as the starting point for every new jQuery plugin.