jQuery Extensions Aren't Just for Plugins
I don't typically think about extending jQuery for page specific code. Normally I reserve that for plugin authoring, but I was working on a screen the other night and I found myself calling a function in a few places and passing it a jQuery object. This function would iterate over the elements and do blabady-blah whatever. I realized that I could make this a whole lot cleaner by writing it instead as a method on the jQuery object.
Originally it looked something like this:
[js]var MyPage = {
actOnItems: function(items) {
$(items).each(function() {
...
});
},
needsToActOnItems: function() {
MyPage.actOnItems($("div :input"));
}
};[/js]
That isn't a bad way to do it necessarily, but I think it makes the code a lot simpler and cleaner to read if I just extend jQuery with the method instead.
[js](function($) {
$.fn.actOnItems: function() {
return this.each(function() {
...
});
};
})(jQuery);
var MyPage = {
needsToActOnItems: function() {
$("div :input").actOnItems();
}
};[/js]
The jQuery extension stays with the rest of the page specific JavaScript, but now we have abstracted it out so it can be used like any other jQuery method. This also allows us to chain it and reduce the risk of confusing the future maintainer of the code.
Be careful not to go crazy with this though. As with anything, only do it when and where it makes sense.