A plugin with methods and destroy
Call methods by name ($el.plugin('open')), keep state in data(), and clean up in destroy.
jQuery · A plugin with methods and destroyAdvanced
(function ($) {
const NAME = 'panel';
const methods = {
init(opts) {
return this.each(function () {
if ($(this).data(NAME)) return;
const state = { open: false, opts: $.extend({ speed: 150 }, opts) };
$(this).data(NAME, state).hide();
});
},
open() { return this.each(function () { $(this).data(NAME).open = true; $(this).show(); }); },
close() { return this.each(function () { $(this).data(NAME).open = false; $(this).hide(); }); },
isOpen() { return !!this.first().data(NAME)?.open; },
destroy() { return this.each(function () { $(this).removeData(NAME).off('.' + NAME).show(); }); },
};
$.fn[NAME] = function (method, ...args) {
if (methods[method]) return methods[method].apply(this, args);
if (!method || typeof method === 'object') return methods.init.call(this, method);
$.error('Method ' + method + ' does not exist on jQuery.' + NAME);
};
})(jQuery);
$('#p').panel().panel('open');pluginmethodsdatadestroystate