Home » JavaScript » jQuery » Things I learned creating a jQuery Plugin (Part II)

About Antonio Santiago

Antonio Santiago
A Computer Science as profession and hobby. Firm believer of Software Engineering and a lover of Agile methodologies. There is no ring to rule them all, every place needs to forge its own master ring. His main field of experience is the Java ecosystem, and he has also worked actively with many related web technologies while looking to improve the client side of web applications.

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:

//
// Default options
//
$.fn[pluginName].defaults = {
    opt_A: ""
}; 

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:

$.fn[pluginName] = function(options) {
    return this.each(function() {
        new Plugin(this, options);
    });
} 

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:

function Plugin(element, options) {
    // Store references to the selected element
    this.el = element;
    this.$el = $(element);

    // Merge passes options with defaults
    this.options = $.extend({}, $.fn[pluginName].defaults, options);

    // ...other code here...

    // Initialize the plugin instance
    this.init();
} 

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.

//
// Plugin prototype
//
Plugin.prototype = {

    //
    // Initialize the plugin instance
    //
    init: function() {
        ...
    },

    //
    // Free resources
    //
    destroy: function() {
        ...
    },

    //
    // Public method
    //
    publicMethod: function() {
        ...
    },

    //
    // Private method (it starts with an underscore)
    //
    _privateMethod: function() {
        ...
    }

} 

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:

$.fn[pluginName] = function(options) {
    var args = arguments;

    if (options === undefined || typeof options === 'object') {
        // Creates a new plugin instance, for each selected element, and
        // stores a reference withint the element's data
        return this.each(function() {
            if (!$.data(this, 'plugin_' + pluginName)) {
                $.data(this, 'plugin_' + pluginName, new Plugin(this, options));
            }
        });
    } 

    ...
}; 

That occurs in the line:

$.data(this, 'plugin_' + pluginName, new Plugin(this, options)); 

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:

//
// Free resources
//
destroy: function() {

    // Remove elements, unregister listerners, etc

    // Remove data
    this.$el.removeData();
} 

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 parameterfieldSeparator to a value different from the default options value and registering a callback function for the onTagAdded event:

$('#inputID').tagger({
  fieldSeparator: '|'
  onTagsAdded: function(tags) {
    console.log('Added new tag: '+tags+'\n');
  }
}); 

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:

//
// Default options
//
$.fn[pluginName].defaults = {
    fieldSeparator: ",",
    readOnly: false,
    // Callback invoked when user calls the 'tags' method
    onTagsAdded: function() {
    },
    // Callback invoked when user calls the 'remove' method
    onTagsRemoved: function() {
    },
    // Callback invoked when user calls the 'clear' method.
    // Note: Internally the 'clear' method uses the 'remove'.
    onClear: function() {
    },
    // Callback invoked when the user click a tag label
    onClick: function() {
    }
}; 

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

// Adds one or more tags
// ...
//
tags: function(tags) {
      ...
      // Call the callback
      this.options.onTagsAdded.call(this, tags);
      ...
    }
}, 

Note how we have forced to set thethis 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:

  1. http://docs.jquery.com/Plugins/Authoring
  2. http://www.websanova.com/tutorials/jquery/the-ultimate-guide-to-writing-jquery-plugins
  3. http://jqueryboilerplate.com/
  4. https://github.com/zenorocha/jquery-plugin-patterns
  5. http://coding.smashingmagazine.com/2011/10/11/essential-jquery-plugin-patterns/
  6. http://addyosmani.com/resources/essentialjsdesignpatterns/book/#jquerypluginpatterns
Reference: Things I learned creating a jQuery Plugin (Part II) from our WCG partner Antonio Santiago at the A Curious Animal blog.
(0 rating, 0 votes)
You need to be a registered member to rate this.
1 Comment Views Tweet it!
Do you want to know how to develop your skillset to become a Web Rockstar?
Subscribe to our newsletter to start Rocking right now!
To get you started we give you our best selling eBooks for FREE!
1. Building web apps with Node.js
2. HTML5 Programming Cookbook
3. CSS Programming Cookbook
4. AngularJS Programming Cookbook
5. jQuery Programming Cookbook
6. Bootstrap Programming Cookbook
and many more ....
I agree to the Terms and Privacy Policy

1
Leave a Reply

avatar
1 Comment threads
0 Thread replies
0 Followers
 
Most reacted comment
Hottest comment thread
1 Comment authors
Aaron Saray Recent comment authors

This site uses Akismet to reduce spam. Learn how your comment data is processed.

  Subscribe  
newest oldest most voted
Notify of
Aaron Saray
Guest

Be careful when using $.removeData() without specifying the name in your destroy() method. You don’t want to clobber other plugins who might also be using $.data() to store different information on that element.