Reuse your JavaScript as jQuery Plugins
Today’s guest post is from Christopher Haupt of Webvanta, an Engine Yard partner. Christopher is co-founder of Webvanta, co-host of the Learning Rails podcast, and frequent contributor at Ruby and Web Development and Design related conferences, meet-ups, and publications.
Webvanta is co-sponsoring the North Bay Web Design Conference on April 12, 2011 in Rohnert Park, CA. To check out the speaker lineup and to register to attend visit the North Bay Web Design Conference event site.
Our team finds that we get the greatest leverage out of our existing collection of code snippets by organizing them into well structured, easy to maintain libraries of pluggable modules. This is the first article in a two part series. In this article, we take a whirl-wind tour of how to create reusable modules with front-end JavaScript code using the popular jQuery library. In my follow-up article, we will briefly examine the Web Storage technology that has come out of the HTML5 specification process and then show how simple it is to wrap it within a jQuery plugin.
If you go back and look through the last few web app projects you’ve completed, you probably will find that you have accumulated a variety of snippets of JavaScript that may have even been tweaked to be reused in follow-on projects. If you haven’t yet organized these bits of code in a particular way, you may want to consider leveraging an existing framework that provides well-defined structure for code reuse.
Our team primarily uses jQuery, a very straightforward and easy to use JavaScript library originally created by John Resig back in 2006. If you are new to jQuery, we recommend the excellent jQuery in Action book and jQuery’s own website for pointers to tutorials and documentation.
jQuery has two logical components. The base jQuery library includes a powerful CSS-like selector mechanism, easy methods to manipulate the DOM, rich effects, Ajax support, utilities, and more. The jQuery UI library provides a collection of user interface widgets. These two parts of jQuery form the basis of a rich ecosystem that is further enhanced with many plugins. Writing jQuery plugins is pretty straight-forward once you are familiar with the basic conventions.
Conventions Conventions
If jQuery is a fit for your project, you can utilize its conventions to reap the benefits of a consistent code style, logical approach to working with data, and to easily leverage other basic building blocks of code.
Three particular best practices are self-evident with a quick review of the jQuery community (see the plugin authoring guidelines for more details).
First, files, functions, data, and events should follow naming rules to help form and maintain namespaces. Files will typically use the pattern of “jquery-prefix-name-version.js”. “jquery” identifies the file as a jQuery compatible piece of code, often a plugin. “prefix” is an optional word, acronym, or hyphenated phrase that identifies an organization or group of related files. “name” is the name of the plugin. “version” is usually the major and minor version numbers of the code, e.g. jquery-webvanta-icon-picker-1.0.js.
Functions, data, and events should use specific techniques outlined in the jQuery Plugin Authoring guidelines to minimize conflicts between different plugins.
A second convention deals with the common issue of protecting your jQuery plugin from interference by other JavaScript libraries or function namespaces. It also typically includes a simple trick for safely accessing the shorthand “$” variable which holds a reference to the jQuery object. By defining a self executing anonymous function that forms a closure, you keep your code reasonably isolated:
(function($){
$.iconPicker = function() {
// Your code goes here
}
})(jQuery);
The anonymous function runs as soon as it is defined, passing the global “jQuery” value as a parameter, where it gets assigned to the local parameter name “$”, which is then accessible to the internal scope of the function regardless of what “$” may be outside.
A third convention details how parameters are passed to your plugin. Rather than long and complicated function signatures with many individual parameters (e.g. icon-picker(element, color, size, effect, delay)), utilize the technique of passing in a single JavaScript literal object, which simulates a collection of name/value pairs. This makes for more readable code, and makes it easy to implement default values and to allow for arbitrary missing or added parameters:
$.iconPicker({element: el, color: 'blue', size: 3, effect: 'shrink', delay: 1000});
You’ll use this technique most commonly when writing a plugin with many optional parameters. For Rubyists, this may look similar to using a tailing hash in the parameter list to pick up arbitrary or named parameters.
Plain Old Utility Function Pattern
Utility functions are typically small routines that accomplish some basic self-contained task, such as string or date-time manipulation, working with cookies, or logging information. In the jQuery world, the usual approach to organizing such code is to attach these functions off of the main jQuery namespace. Remembering our conventions discussed earlier, this might look like:
(function($){
$.webvantaUtils = {};
$.webvantaUtils.readCookie = function(name) {
var ne = name + "=",
ca = document.cookie.split(';');
for(var i=0;i < ca.length;i++) {
var c = ca[i];
while (c.charAt(0)==' ') c = c.substring(1,c.length);
if (c.indexOf(ne) == 0) return c.substring(ne.length,c.length);
}
return null;
}
})(jQuery);
Note we have namespaced our cookie related function under a higher level namespace organized in this case by a company library.
Once defined, you can use such a function elsewhere via simple reference (you could use “$” rather than jQuery if you wish and you know that it isn’t being used for some conflicting purpose in the scope of the call):
var myUser = jQuery.webvantaUtils.readCookie('user_info');
Wrapped Set Function Pattern
If you have utilities that act on DOM elements, you should tie in to jQuery’s ability to operate on a collection of DOM elements called a wrapped set.
Instead of assigning our functions to the top-level jQuery namespace, we instead connect to the “fn” object, which gains us access to the wrapped set through the “this” variable.
Let’s say you have some utility code that counts how many times any of your form input elements contain a particular letter sequence:
(function($){
$.fn.redAlert = function(badValue) {
var badValueFound = 0;
this.each(function() {
if ($(this).val().toLowerCase().indexOf(badValue.toLowerCase()) >= 0)
badValueFound = badValueFound + 1;
});
return badValueFound;
};
})(jQuery);
We use the wrapped set found in the first “this” and call an iterator on it to walk through each value in the set. Within the function passed to the “each” iterator, the value of “this” changes to point to one of the wrapped set’s DOM elements. We can reconstitute that element as a jQuery object with the $(this) idiom, and use it as we wish…here to compare some string values.
You might use the plugin like so:
if ($("form input:text").redAlert('Stink') > 0)
alert("Something smells in the form");
In this contrived example, we are returning an integer value to accomplish our goals.
Adding Chaining
If you are not returning a specific value from your function, with only a small tweak you can gain the benefit of being able to have your utility chained together with other jQuery code. Such plugin chains are often used to accomplish complex actions easily and efficiently.
The trick is to simply return the “this” value that contains the wrapped set:
(function($){
$.fn.redAlert = function(badValue) {
return this.each(function() {
if ($(this).val().toLowerCase().indexOf(badValue.toLowerCase()) >= 0)
$(this).addClass('error').css('background-color', 'red');
});
};
})(jQuery);
So I can then construct a chain of calls:
$("form input:text").redAlert('Stink').addClass('scanned');
But Where is the Namespacing?
You may have noticed that we skipped an important step when implementing our redAlert plugin. It isn’t namespaced.
Simply pushing our function into a sub-object, like we did for our readCookie utility plugin won’t work:
(function($){
// BAD, THIS WON'T WORK
$.fn.webvantaUtils = {};
$.fn.webvantaUtils.redAlert = function(badValue) {
return this.each(function() {
if ($(this).val().toLowerCase().indexOf(badValue.toLowerCase()) >= 0)
$(this).addClass('error').css('background-color', 'red');
});
};
})(jQuery);
When doing so, we lose access to the wrapped set contained in the initial “this” variable. It instead points to the webvantaUtils object, not the wrapped set.
To get around this issue, the jQuery recommendation is to organize all of your plugin methods within an object literal, then use a dispatcher technique to access the desired functions:
(function( $ ){
var methods = {
init : function( options ) { },
redAlert : function(badValue) {
return this.each(function() {
if ($(this).val().toLowerCase().indexOf(badValue.toLowerCase()) >= 0)
$(this).addClass('error').css('background-color', 'red');
});
}
};
$.fn.webvantaUtils = function( method ) {
// Method dispatch logic
if ( methods[method] ) {
return methods[ method ].apply( this, Array.prototype.slice.call( arguments, 1 ));
} else if ( typeof method === 'object' || ! method ) {
return methods.init.apply( this, arguments );
} else {
$.error( 'Method ' + method + ' does not exist on jQuery.webvantaUtils' );
}
};
})( jQuery );
And then call it via:
$("form input:text").webvantaUtils('redAlert','Stink').addClass('scanned');
This approach is a little more complicated, but ensures that the namespace is “clean”. It uses a few JavaScript tricks to accomplish its goal. First, the actual functions of our plugin are stored as attributes of the literal object called “methods”. Second, the entry point to our plugin is the “namespace”, here “webvantaUtils”.
When we invoke the plugin through this entry point, it first checks to see what kind of parameters were passed in. That may sound odd, since it looks like the entry point only takes one named parameter “method”. Regardless of the number of named arguments, JavaScript doesn’t complain if “extra” parameters are passed in.
The expectation is that the first parameter will either be nothing at all, an object of some kind, or a string naming the desired function.
First the entry point tries to use the value of “method” to find a matching attribute of the “methods” object. If that fails, it next checks to see if “method” is itself an object OR it is a null or undefined value. In that case, with our sample above, an optional “init” method is invoked. This is purely convention, and could be stripped out if you don’t need to initialize anything. “init” is a handy place if you have default values you need to set up or override.
If none of the previous conditions are true, then an error message gets displayed in the console.
Now, in the case of both the init function or a matched function name being found in the methods object, the code uses the JavaScript apply() method. apply() is a method on the Function object. apply()’s job is to execute the receiver’s function, and it uses its first parameter to set what the value of “this” will be inside of that function. The second parameter is an array which is passed to the called function as its parameter list.
Here we see the special Argument object being used in the variable called “arguments”. JavaScript always sets “arguments” to contain the complete parameter list of a called function. In this case, it is used to pass on any parameters sent to the entry point (other than the first one in the case of a name string being passed in to invoke a plugin function).
This may be slightly confusing, yet digging in to the JavaScript is educational. The good news is that you can focus on using this “plugin pattern” as a template for your own code and mostly ignore the rest of the details when getting started.
The jQuery Plugin Authoring guidelines contain even more examples.
UI Widget Factories
While we won’t get in to the details here, we should point out that if you are trying to build user interface code, or need to construct more complicated, statefull plugins, a worthwhile plugin architecture to review is the jQuery UI Widget factory mechanism. Widgets provide additional conventions for organizing code including dealing with defaults and options on a per widget basis, code hiding of “private” functions used by the widget, and ways of exposing widget data accessors, events, and other functionality.
A Wrap of Plugins
We’ve briefly explored the basics that will permit you to clean up and possibly refactor your existing JavaScript code into reusable jQuery plugins. With the information presented in this article, and the Plugin Authoring notes on the jQuery.org site, you should have all you need to get started. Next time, we will take a peek at a relatively new client-side storage technology that has come out of the HTML5 efforts and build a small jQuery plugin that wraps it with a generic API.
About Webvanta
Webvanta provides a hosted CMS and site-building services for designers and front-end developers. Their platform is built on Ruby on Rails and is hosted by Engine Yard. Webvanta offers a free ebook, 5 Tips for Building Better Sites, that summarizes the key lessons learned from being involved with more than 200 sites in the past two years.
Webvanta is co-sponsoring the North Bay Web Design Conference on April 12, 2011 in Rohnert Park, CA. To check out the speaker lineup and to register to attend visit the North Bay Web Design Conference event site.
Share your thoughts with @engineyard on Twitter