Advanced jQuery Plugins

This is *so* cool: http://yehudakatz.com/2009/04/20/evented-programming-with-jquery. It’s a really elegant way of writing jquery plugins.

It basically splits the plugin into 2 parts: initialization of custom events and the code that handles those events. The code that handles the events is the “meat and potatoes” and is defined as a public property of the plugin; however you can also pass in a replacement object to the plugin function, with a new set of event handlers — and that’s the really clever bit.

If you want to extend the plugin, you just clone the base handler-object and either chain your own handlers or replace the existing ones. This is like the Decorator pattern but for javascript event handlers. So for example, the plugin might turn the text red when you click it. If you wanted it to also bold the text, you clone the base object and add a new “listener” for the “changeColor” event which will make the text bold.

The pattern makes is very easy to unobtrusively extend the plugin. Previously I’d have used callback hooks but with this style of plugin there’s no need. It’s even better than callback functions because you can completely overwrite the “meat and potatoes”.

Shit like this is why I like Javascript :-).

Leave a Reply