SyntaxStudy
Sign Up
jQuery Plugin with Multiple Methods
jQuery Advanced 5 min read

Plugin with Multiple Methods

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.

Example
$.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");
Pro Tip

This multi-method pattern is used by jQuery UI and most production plugins.