jQuery has two types of utility "plugins" (for lack of a better term). The first is adding a method to the actual jQuery object and is also the easiest to implement, The second is to add to jQuery object instances which expect specific things to happen (chaining, iteration, context management, event, etc.).
Utility functions
This is the easy one because your not manipulating jQuery objects but instead just extending jQuery as if it was any normal JavaScript object. Simply assigning a function to jQuery (or $
for short) does the trick.
jQuery.myNewRadUtility = function myNewRadUtility(input, options) {
// Do something with input and options
return someValue; // return what you want
};
// Use it in your other code like so:
$.myNewRadUtility(input, options); // Or what ever you plan on doing
As you can see it's just a function like any other except your assigning it to a property on the jQuery object.
To make things more generic / hybrid approach you can separate the function and write it as if it was generic and then attach it to jQuery in a jQuery specific file or pragmatically.
function myNewRadUtility() {
// Do one and only one amazing thing here.
}
// If we have jQuery then lets use it.
if (jQuery) {
jQuery.myNewRadUtility = myNewRadUtility;
}
// Or if you need to massage the input / output to conform to jQuery then
if (jQuery) {
jQuery.myNewRadUtility = function() {
// Massage the input here
var result = myNewRadUtility();
// Massage the output here
return result;
};
}
jQuery plugins
This is a little more advance as you have to consider how jQuery objects expect to be used. First you attach to the prototype as you would above using jQuery's fn
property. Then you have to manage the jQuery objects that the utility needs to work with. This means iterate over them. Finally you need to return the same or new instance depending on the purpose of the utility your creating (more often then not just return this
).
jQuery.fn.myNewRadUtility = function myNewRadUtility() {
return $(this).each(function() {
// Do something with $(this)
});
};
// Use it in your other code like so:
$('p').myNewRadUtility();
Obviously there is a lot more to it and there is a lot you can do. But this is the bare minimum to get a taste.