What is a JQuery plug-in:
A JQuery plug-in is the JavaScript equivalent of an extension method. Let's look at plug-in syntax:
$.fn.stretch = function(multiple) {
this.each(function() {
var $t = $(this);
$t.height($t.height * multiple);
$t.width($t.width * multiple);
});
return this;
};
I have created a plug-in that multiplies the height and width of an element selected by the multiple passed. (beware, this was slapped this together for demo purposes).
$('#smallDiv').stretch(2);
The method operates on $(this)
, the object it is attached to, and returns an object, allowing for further
Here is a good guide to a range of JQuery Plugin Design Patterns -- some meant to optimize performance, others interoperability / chaining, mutability, etc.
The benefits of a JQuery plug-in:
1) Chaining
$('#smallDiv').css("background-color", "beige").stretch(2);
2) Re-Usability
I admit this is a forced example, but still...
$('#smallDiv').stretch(2).stretch(1.5);
3) Modularity of scope
The code within our plug-in no variable scope to worry about. It is completely self-contained using only local variables.
4) Readbility
I assume here that your plug-in is appropriately named
To DOM or not to DOM:
Plug-ins can be useful in many ways
I suspect 90% of plug-ins are used for DOM manipulations. And chaining is a great advantage.
But JQuery already has many array extension methods:
$.distinct([1, 2, 2, 3])
$.union([1, 2, 2, 3], [2, 3, 4, 5, 5])
$.intersect([1, 2, 2, 3], [2, 3, 4, 5, 5])
$.except([1, 2, 2, 3], [2, 3, 4, 5, 5])
(all anove borrowed from Kristian Abrahamsen GitHub Repo)
And Plugins for Strings, Cookies, etc exist and can/should be considered
The disadvantages of a JQuery plug-in:
Global isn't always noble: Your nifty new stretch()
Plugin can be used on anything. Is that good or bad? You decide. Who should use it? Who shouldn't? What elements should it be used on?
If you don't want repeated use, don't create a plug-in. I'm sure Plenty of Developers on your team are too creative as it is.
Planning is a must! Refer to this Brolick Blog Guide to Developing Plugins
Between the Brolick guide and the patterns reference, you'll notice there are many mistakes and issues you can cause from sloppy plugin development. The most common of these are poor performance and memory leaks. Both are underestimated is potential severity and are rampant and frequent in Plugin development.