jQuery in Action

194
CHAPTER 7
Extending jQuery with custom plugins
The implementation of this function is shown in listing 7.1.
(function($){
$.toFixedWidth = function(value,length,fill) {
var result = value.toString();
if (!fill) fill = '0';
var padding = length - result.length;
if (padding < 0) {
result = result.substr(-padding);
}
else {
for (var n = 0; n < padding; n++)
result = fill + result;
}
return result;
};
})(jQuery);
This function is simple and straightforward. The passed value is converted to its
string equivalent, and the fill character is determined either from the passed
value or the default of
0
b
. Then, we compute the amount of padding needed
c
.
If we end up with negative padding (the result is longer than the passed field
length), we truncate from the beginning of the result to end up with the specified
length
d
; otherwise, we pad the beginning of the result with the appropriate
number of fill characters
e
prior to returning it as the result of the function
f
.
Simple stuff, but it serves to show how easily we can add a utility function. And,
as always, there's room for improvement. Consider the following exercises:
As with most examples in books, the error checking is minimal to focus on
the lesson at hand. How would you beef up the function to account for
caller errors such as not passing numeric values for
value
and
length
?
What if they don't pass them at all?
We were careful to truncate numeric values that were too long in order to
guarantee that the result was always the specified length. But, if the caller
passes more than a single-character string for the fill character, all bets are
off. How would you handle that?
What if you don't want to truncate too-long values?
Now, let's tackle a more complex function in which we can make use of the
$.toFixedWidth()
function that we just wrote.
Listing 7.1
Implementation of the $.toFixedWidth() utility function
b
c
d
e
f


Другие страницы

 
Cкачать книги бесплатно без регистрации в электронном виде (pdf, chm, txt).Вы можете читать книги онлайн на нашем сайте литературного портала книг.Большая подборка учебников, пособий, интересных книг.Электронные книги на английском языке скачать бесплатно без смс.