Skip to content

A Highly Configurable And Mutable Plugin Pattern

Iurii Kucherov edited this page Aug 5, 2015 · 2 revisions

A Highly Configurable And Mutable Plugin Pattern

From Learning JavaScript Design Patterns, a book by Addy Osmani.

In this pattern, similar to Alex Sexton's prototypal inheritance plugin pattern, logic for our plugin isn’t nested in a jQuery plugin itself. We instead define our plugin logic using a constructor and an object literal defined on its prototype. jQuery is then used for the actual instantiation of the plugin object.

Customization is taken to the next level by employing two little tricks, one of which we’ve seen in previous patterns:

  • Options can be overridden both globally and per collection of elements/
  • Options can be customized on a per-element level through HTML5 data attributes (as shown below). This facilitates plugin behavior that can be applied to a collection of elements but then customized inline without the need to instantiate each element with a different default value. We don’t see the latter option in the wild too often, but it can be a significantly cleaner solution (as long as we don’t mind the inline approach). If wondering where this could be useful, imagine writing a draggable plugin for a large set of elements. We could go about customizing their options as follows:
$( ".item-a" ).draggable( {"defaultPosition":"top-left"} );
$( ".item-b" ).draggable( {"defaultPosition":"bottom-right"} );
$( ".item-c" ).draggable( {"defaultPosition":"bottom-left"} );
//etc

But using our patterns inline approach, the following would be possible:

$( ".items" ).draggable();
<li class="item" data-plugin-options="{"defaultPosition":"top-left"}"></div>
<li class="item" data-plugin-options="{"defaultPosition":"bottom-left"}"></div>

And so on. We may well have a preference for one of these approaches, but it is just another variation worth being aware of.

  1. Code
  2. Usage

Further Reading