Sunday, March 7, 2010

jQuery Plugins

In reference to this

It may not look like it from my other blog entries, but I really am a programmer.

Lately I've been working a lot with CouchDB as both a database and an application server. As part of getting up to speed, I've jumped into JavaScript. Somewhere along the way I found jQuery and ended up writing a plugin.

Since I'm such a perfectionist and because I'd armed myself with some knowledge of JavaScript's good parts, I wasn't 100% satisfied with the way some jQuery plugins were written.

Below is my take on a jQuery plugin template. You can see it in action in my autoExpandingList plugin (demo). I'll probably put it on GitHub eventually, but for now it's on jsbin (great tool, by the way).


/**
* jQuery.PLUGINNAME
*
* @author YOUR NAME
*
* NOTES/DESCRIPTION
*
*/
"use strict";
(function ($) {

$.fn.pluginName = $.fn.pluginName || (function () {

var defaults = {
//Default configuration
};

// Utility functions that you use inside your plugin that
// don't rely on per-invocation closures should go here.
// This is also a good place to keep track of any global
// state information that your individual plugin instances
// may want to make use of.
// This is your plugin function, what people will call
// with $("li").pluginName(...);
return function (settings) {

// Settings are cached per selector/invocation,
// not per affected element. This is a bit of a memory optimization.
// If you need/want your settings to be per element,
// just move this line to inside the each() below.
settings = $.extend({}, defaults, settings);

this.each(function () {
//Cache 'this' because it may change with scope,
// depending on what you do below.
var that = this;

/* Insert your special sauce here.
* Perform your operations on 'this' or 'that'
*and it will affect each element in the selector.
*/
});

// This is important in jQuery land.
// It allows chaining. Even if you don't make use of chaining,
// people using your plugin may.
return this;
};
}());
}(jQuery)); //Pass in the jQuery object by name in case $ is used


Some other things that I found to make things better were JSLint (which the above template passes) and js-beautify (which was used to format the above).

js-beautify had a small bug where it would make things ugly if you were using an empty object literal ($.extend({}, defaults, settings)'), but a one-liner patch was all it took to clear that up and I've already submitted it and had it applied, so it's ready for you to use!

I've also been teaching myself Python, so maybe I'll have some posts on that in the future as well. And maybe some thoughts on CouchDB.

No comments: