Sunday, January 10, 2010

Creating a plugin for jQuery ( Macros in jQuery)

Creating a plugin for jQuery is incredibly simple and is a very useful way to abstract complex behaviours so that they can be used repeatedly as part of your jQuery "chains".

But, when the time comes, and you’re faced with the decision to either create a jQuery plugin or to simply create a regular function, everything suddenly becomes quite complicated. First, you'll wonder whether the piece of behaviour you want to abstract is best kept under the jQuery namespace, and then you'll doubt its applicability to the DOM-centred jQuery chain, and then sometimes you’ll recede to something you’re much more comfortable with, a regular ol' JavaScript function.

If we forget about the plugins available online, and we simply focus on your plugins, made and used within a specific project, then the question of whether a plugin is really the right route becomes all the more difficult to answer. Are you going to benefit from extending jQuery’s API? Will the readability of your code benefit?


For example:

function applyColors(elems) {
    $(elems).css({
        color: config.color,
        backgroundColor: config.bgColor,
        borderColor: config.bdColor
    });
}
 
// Call it:
var myElems = $('div.something');
applyColors(myElems);

applyColors encapsulates some behaviour that is needed frequently, and that’s why it’s been abstracted into a function. To some, this approach is lacking in that it doesn’t harness the full power of jQuery, and more specifically, jQuery’s plugin mechanism. How about this:

jQuery.fn.applyColors = function( {
    return this.css({
        color: config.color,
        backgroundColor: config.bgColor,
        borderColor: config.bdColor
    });
};
 
// Call it:
$('div.something').applyColors();

Cleaner? More readable? I think so.
Many developers are not prepared to extend jQuery’s API with their own simple abstractions. I don’t know why. But, I hope, that jQuery macros can help in lowering the barrier to extending jQuery. For Details

No comments:

Post a Comment