jQuery is a simple, yet powerful JavaScript library, which really changed my point of view of JavaScript-ing. A new wave JavaScript they call it and it receives this title righteously. The code you create is a pure elegance.
You start with 10 lines of jQuery that would have been 20 lines of tedious DOM Javascript. By the time you are done it's down to two or three lines and it couldn't get any shorter unless it read your mind.
But of course it can get shorter. It can get shorter by refactoring your script into jQuery plugin.
When it comes to writing, plugins people (including me) usually back off in horror. I heard about jQuery plugins long ago, but never dared to write one. Somewhere in my mind crept a thought, that
- It must be hard and thus left only to true masters
- It must require a deep knowledge of jQuery
- what could I possibly gain?
(I come from a Java world if you wonder).None of the above is true. Writing jQuery plugin is as easy as writing jQuery script. It does not require any special knowledge. All that is needed, is to extend a jQuery object. Something like
$.fn.myPlugin = function() {
$this = $(this);
// plugin code
return $this;
}
Remember? This is JavaScript, not Java and the code above is the only thing needed to create a plugin. Inside the function,
$this is reference to the jQuery object the plugin was called at.
$("table").myPlugin().addClass("surprise");
Now,
$this is table and you can do all sorts of things with it. Because the plugin returns
$this, jQuery operations can be chained.
By extending jQuery object, you do not only inherit its fields and methods, you inherit its elegance.
Now, back to my question, what could you possibly gain by creating a plugin? Mainly
Now it's time to show some real life example. I have been using a script, to make each row of a table clickable.
$("table tr").click(function() {
location.href = 'edit.html?id=' + $("td:first a", $(this)).html();
});
Whenever I wanted to make the rows clickable I copied the snippet and changed the url or parameter name. But with the plugin..
$.fn.clickable = function(settings) {
defaults = {
href: 'edit.htm',
paramName: 'id'
}
settings = $.extend(defaults, settings); //overwrite the defaults with provided setings
$this = $(this);
$("tr", $this).click(function() {
location.href = settings.href + '?' + settings.paramName + '=' + $("td:first", $(this)).html();
});
return $this;
}
..I can use it:
$("table").clickable();
or when I am not confident with default settings, I can change them
$("table").clickable({href: 'change.htm'});
If you want to know more about plugins, read the official plugin authoring guide or Mike Alsup's excellent plugin development pattern.
I hope I inspired you.