Plugin Methods Pattern
Support multiple methods in one plugin by checking the first argument: if a string, call the named method; if an object, initialize with options.
Support multiple methods in one plugin by checking the first argument: if a string, call the named method; if an object, initialize with options.
$.fn.slider = function(method, ...args) {
const methods = {
init(opts) { /* setup */ },
next() { /* go to next slide */ },
prev() { /* go to prev slide */ },
destroy() { /* clean up */ }
};
if (methods[method]) {
return methods[method].apply(this, args);
} else if (typeof method === "object" || !method) {
return methods.init.apply(this, [method, ...args]);
}
};
$(".slider").slider({ autoplay: true });
$(".slider").slider("next");
This multi-method pattern is used by jQuery UI and most production plugins.