A Highly Configurable and Mutable Plug-in Pattern
In this pattern, similar to Alex Sexton’s prototypal inheritance plug-in pattern, logic for our plug-in isn’t nested in a jQuery plug-in itself. We instead define our plug-in logic using a constructor and an object literal defined on its prototype. jQuery is then used for the actual instantiation of the plug-in 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 plug-in 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 you’re wondering where this could be useful, imagine writing a draggable plug-in 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();
html<liclass="item"data-plugin-options="{"defaultPosition ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access