Monday, October 27, 2008

I haven't written about jQuery yet.

I realized that while I've had jQuery listed as an interest of mine for all this time I still haven't written about it. Shame on me.

One of the coolest things about jQuery, aside from the fact that it is generally kind enough to stay out of your way and let you write YOUR javascript the way you want to with just a bit of help from it (unlike some other JS libraries *cough*prototype*cough*), is the rather robust extensibility. It's almost trivial to write your own plugins for jQuery, which other people can then simply include and use like it was any part of the library. You can even override or extend existing jQuery functionality if you wanted to.

On a recent project I had to add functionality to a page to create a dynamic list of filters for some log information, which was presented on a table. The filters had different types, some were time/date fields, some were plain text, and some you could pick from a preset list of values.

Some of my favorite programming features and APIs are the kind where you can setup a large list of parameters, instantiate an object or call a method and let 'er rip. Plugins, especially jQuery plugins, really lend themselves to this sort of programming.

I ended up using this approach to write my filter feature, eventually realizing I could turn it into a jQuery plugin without too much effort.

Here is a link to my actual .js file for the plugin-ized version. And here is a basic example of how to use it.

$(document).ready(function() {
$('#filterform').filterselector(
{filters:[{value: 'state', name: 'Status', type: [[0,'Open'],[1,'Closed']]},
{value: 'customer', name: 'Customer', type: 'text'},
{value: 'opened', name: 'Date Opened', type: 'datepicker'},
);
});
The code above is used by the plugin to create the HTML to display the initial form, which consists of 3 buttons and a single drop down list. The dropdown list is constructed using the value and name attributes, where value is the and name is the pretty name. It's probably easiest if value corresponded to the name of a database field somewhere, for ease of writing the backend.
When an option is selected from the original dropdown, the script looks at the type in that filters array to decide what to add. The types of "text" and "datepicker" both create text fields, but the datepicker has a special event attached to it to popup the jQuery datepicker and let you pick a range of dates. The only other option right now is to set an array like "[[0,'Open'],[1,'Closed']]", each internal tuple (python terminology), consists of a value and a name. The plugin uses these to make another dropdown list using those tuples.

Right now creating your own types involves adding a new elseif to the code, but it'd be pretty easy to add a hook to write new type handling functions.

Anyway, I finally wrote about jQuery. Even if I suck at writing.

--PXA, apologizes for this mess.

No comments: