jQuery in Action

Writing custom utility functions
193
This seems like an easy way out but proves to be less than optimal for more com-
plex functions. What if the function body utilizes lots of jQuery methods and
functions internally to get its job done? We'd need to use
jQuery
rather than
$
throughout the function. That's rather wordy and inelegant; besides, once we use
the
$
, we don't want to let it go!
So looking back to the idiom we introduced in section 7.2.2, we can safely
write our function as follows:
(function($){
$.say = function(what) { alert('I say '+what); }
})(jQuery);
such a trivial function) because it protects the use of
$
when declaring and defin-
ing the function. Should the function ever need to become more complex, we can
extend and modify it without wondering whether it's safe to use the
$
or not.
With this pattern fresh in our minds, let's implement a non-trivial utility func-
tion of our own.
7.3.1 Creating a data manipulation utility function
Often, when emitting fixed-width output, it's necessary to take a numeric value
and format it to fit into a fixed-width field (where width is defined as number of
characters). Usually such operations will right-justify the value within the fixed-
width field and prefix the value with enough fill characters to make up any differ-
ence between the length of the value and the length of the field.
Let's write such a utility function that's defined with the following syntax:
Function syntax: $.toFixedWidth
$.toFixedWidth(value,length,fill)
Formats the passed value as a fixed-width field of the specified length. An optional fill char-
acter can be supplied. If the numeric value exceeds the specified length, its higher order dig-
its will be truncated to fit the length.
Parameters
value
(Number) The value to be formatted.
length
(Number) The length of the resulting field.
fill
(String) The fill character used when front-padding the value. If omitted, 0
is used.
Returns
The fixed-width field.


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

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