jQuery: plugin design patterns and anti-patterns

A series of articles on jQuery's plugin design patterns has been scheduled by Fuel Your Coding a couple of months ago. The first article of this series, written by Douglas Neiner, covers the basics of design patterns applied to jQuery plugins. The most interesting part of this article is where Douglas popularizes what can be actually called Widget pattern. It is as follows:

Widget pattern

(function($){
   var MyClass = function(el){
       var $el = $(el);

       // Attach the instance of this object
       // to the jQuery wrapped DOM node
       $el.data('MyClass', this);
   }

   $.fn.myPlugin = function(){
      return this.each(function(){
         (new MyClass(this));
      });
   }

})(jQuery);

Douglas says:

You should use this structure if you need to be able to access the object later that is associated with a DOM element. It is far easier to attach a single object vs several key/value pairs using the data() method. In this approach, you can access the object by calling $('selector').data('MyClass'). This functions more like a widget and is a plugin that maintains state and can adjust its state on the fly

this in this case refers to the newly created object, which accepts as its own property the jQuery object passed during the plugin instantiation. This is a useful pattern that should be used whenever you can, because the data() method binds any kind of data to the jQuery object it references.

Plugin development pattern

Mike Alsup, one of the authors of the Learning jQuery book series, wrote an interesting article on what he called a Plugin development pattern. In a nutshell:

There are a few requirements that I feel this pattern handles nicely:

  1. Claim only a single name in the jQuery namespace
  2. Accept an options argument to control plugin behavior
  3. Provide public access to default plugin settings
  4. Provide public access to secondary functions (as applicable)
  5. Keep private functions private
  6. Support the Metadata Plugin

Private function pattern

Some functions used by the plugin can be kept private in order to establish a distinction between what the plugin must handle internally and what requires user interaction. A useful discussion on this kind of pattern can be found on Stack Overflow.

Anti-patterns

A comprehensive list of common errors occurring during the development process of a plugin has been written down by Remy Sharp in this post. I recommend you to read this post before starting writing any jQuery plugin.

Choosing the appropriate pattern

Choosing the correct and appropriate pattern for our plugins is surely among the most frequently asked questions by web developers. The jQuery Forum provides a useful answer to this question in this forum post.

This entry was posted in by Gabriele Romanato. Bookmark the permalink.

Leave a Reply

Note: Only a member of this blog may post a comment.