Things I learned creating a jQuery Plugin (Part II)

This post is the continuation of the series Things I learned creating a jQuery Plugin.

In the first part we have seen how the structure of a jQuery plugin must be, the plugin entry point (so called wrapper function) and how we can control the behavior of a method as a getter or setter.

Define default options

Your plugin more probably will accept different set of options to allow some configuration. For these reason it is important to define a set of default options which will be applied in cases where no options are specified by the user. Place it within the jQuery wrapper function is a good practice:

Encapsulate your plugin code

A good practice is to encapsulate the logic of our plugin within a function, this way our plugin’s entry point function can easily initialize or call the right method.

For example, in a really simple wrapper function, that simply initializes a plugin’s instance on each selected element, we could write something like:

The plugin constructor

The main part of your plugin is the constructor function. Usually this function is responsible to initialize the plugin, store a reference to the selected element or merge the passed options with the default ones:

Prototype your plugin

Once the Plugin function is defined we can modify its prototype adding all the desired methods we want for our plugin.

There are a couple of methods are a good practice to implement:

  • A init method, which initializes each plugins instance: creating new DOM elements, registering listeners, etc
  • A destroy method, responsible to free any resource used by the plugin: extra elements, unregister listeners, etc.

Other methods can be created within your plugin’s prototype but remember the convention: Use method names starting with underscore for those methods we want to be private.

If you remember the first part of this series, what really happens is when you call a plugin’s method, the wrapper function of our plugin checks if the method’s name starts with underscore and if so then avoids the call.

A note on the destroy method

As we have commented, the destroy method must free any resource used by the plugin instance, like extra created elements, unregister listeners, etc

If you remember the first article, you will notice that the plugin’s instance is stored within the selected DOM element where the plugin is applied:

That occurs in the line:

So, the last action in your destroy method must be always remove the plugin’s instance reference from the element’s data. This can easily done using the reference to the DOM element stored in the plugin instance:

Allow the use of callbacks in our plugin

It is common jQuery plugins allows to register callback functions to be called when an event or action is generated by the plugins. For example, in the tagger plugin the user can be notified when a new tag is added, removed, clicked, etc.

Next lines shows the initialization of the tagger plugin setting the parameter fieldSeparator to a value different from the default options value and registering a callback function for the onTagAdded event:

To achieve this we need to make to main steps:

  1. Define a default and empty callback function in the plugins default options.
  2. At some place of our plugin’s code make a call to the callback function.

Continuing with the sample of the tagger plugin, its default options looks like:

Later, in the method responsible to add new tags to the tag list, a call is made to the onTagsAdded function:

Note how we have forced to set the this object and passed the value of the new added tag to the callback function.

Summary

Ok, this is the end. A short series of two articles to introduce the main concepts to creating jQuery plugins isn’t a bad thing when you are looking for help starting with jQuery and custom plugin development.

Let’s try to summarize the main points we have seen in this couple of posts:

  • Understand the importance of entry point to your plugin. This is handled in a new function on the $.fn object and is responsible to (or can) control: plugin initialization, call to setter or getter methods, simulate private methods, etc.
  • Encapsulate your plugin’s functionalities in a prototyped function
  • Store, if needed, a reference to the DOM element where your plugin is applied to.
  • Remember to implement a destroy method responsible to free all the resources used by your plugin
  • Create a default options object that serves as a base to extend it with the options specified by the user
  • Keep calm and remember try and error is a (necessary) way to learn

References

The web is plenty of great information:

http://docs.jquery.com/Plugins/Authoring

http://www.websanova.com/tutorials/jquery/the-ultimate-guide-to-writing-jquery-plugins

http://jqueryboilerplate.com/

https://github.com/zenorocha/jquery-plugin-patterns

http://coding.smashingmagazine.com/2011/10/11/essential-jquery-plugin-patterns/

http://addyosmani.com/resources/essentialjsdesignpatterns/book/#jquerypluginpatterns

 

2 Responses

  1. Moritz November 6, 2013 / 15:12

    Great Tutorial. It helped me a lot.
    Also your links to the other sites are very useful.
    Only the link to github is broken.
    Best regards.

  2. Adam Bull August 7, 2014 / 16:15

    Great article (and the part one too!) Definitely going to have to try my hand at writing a plugin soon.

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code class="" title="" data-url=""> <del datetime=""> <em> <i> <q cite=""> <strike> <strong> <pre class="" title="" data-url=""> <span class="" title="" data-url="">