HTML and CSS Reference
In-Depth Information
Writing jQuery Plugins
One of the reasons jQuery has become so popular is that it is trivial to write plugins that
integrate with jQuery. This has led to a huge number of plugins freely available under the
MIT license, and also allows you to write your own custom plugins.
A jQuery plugin usually works by performing an operation on an element, or set of elements
returned from a jQuery selection. Just like standard jQuery functions, depending on how the
plugin is written it may be capable of acting on a whole set of elements, or just a single ele-
In this section we are going to write a plugin that can be executed on a form element that has
been selected using jQuery. This plugin will then return an object where the property names
on the object are the form field names, and the values are the values of that field. Effectively
this plugin is going to serialize the values on a form into an object. We will also allow this
plugin to operate in the opposite direction: to de-serialize an object onto a form .
This plugin will take advantage of programming by convention. We will assume that the ob-
ject names and the form field names should always match, even though there will be nothing
in the code that insists on this.
Programming by convention does have disadvantages. For instance, if anyone changed the
name of a field this will result in changes to the property on the objects serialized from that
form, and that may in turn break other code that had expectations about what those prop-
erties would be. Programming by convention can significantly reduce the amount of code
required to implement functionality however.
Plugins work in jQuery by passing the jQuery function to the plugin function, which will
then extend the jQuery function by creating an object with a set of new functions in it.
It is not particularly important that you understand this process, but the boilerplate code for
adding new functions to jQuery looks like this:
(function($) {
action: function() {}
In this case we are adding a single new jQuery function called action . This could then be
invoked as follows:
> $('div').action()
Search WWH ::

Custom Search