jQuery in Action
198
CHAPTER 7
Extending jQuery with custom plugins
The most interesting aspect of this implementation, aside from a few JavaScript
tricks used to keep the amount of code in check, is that the function
tricks used to keep the amount of code in check, is that the function
b
needs
some ancillary data to do its job--in particular:
A regular expression used to match tokens in the pattern
c
A list of the English names of the months
d
A list of the English names of the days
e
A set of sub-functions designed to provided the value for each token type
given a source date
given a source date
f
We could have included each of these as
var
definitions within the function body,
but that would clutter an already somewhat involved algorithm; and because
they're constants, it makes sense to segregate them from variable data.
they're constants, it makes sense to segregate them from variable data.
We don't want to pollute the global namespace, or even the
$
namespace,
with a bunch of names needed only by this function, so we make these declara-
tions properties of our new function itself. Remember, JavaScript functions are
first-class objects, and they can have their own properties like any other Java-
Script object.
tions properties of our new function itself. Remember, JavaScript functions are
first-class objects, and they can have their own properties like any other Java-
Script object.
As for the formatting algorithm itself? In a nutshell, it operates as follows:
Creates an array to hold portions of the result.
Iterates over the pattern, consuming identified token and non-token char-
acters until it has been completely inspected.
acters until it has been completely inspected.
Resets the regular expression (stored in
$.formatDate.patternParts
) on
each iteration by setting its
lastIndex
property to 0.
Tests the regular expression for a token match against the current begin-
ning of the pattern.
ning of the pattern.
Calls the function in the
$.formatDate.patternValue
collection of conver-
sion functions to obtain the appropriate value from the
Date
instance if a
match occurs. This value is pushed onto the end of the results array, and
the matched token is removed from the beginning of the pattern.
the matched token is removed from the beginning of the pattern.
Removes the first character from the pattern and adds it to the end of the
results array if a token isn't matched at the current beginning of the pattern.
results array if a token isn't matched at the current beginning of the pattern.
Joins the results array into a string and returns it as the value of the func-
tion when the entire pattern has been consumed.
tion when the entire pattern has been consumed.
Note that the conversion functions in the
$.formatDate.patternValue
collection
make use of the
$.toFixedWidth()
function that we created in the previous section.