jQuery in Action

Adding new wrapper methods
199
You'll find both of these functions in the file chapter7/jquery.jqia.dateFormat.js
and a rudimentary page to test it at chapter7/test.dateFormat.html.
Operating on run-of-the-mill JavaScript objects is all well and good, but the
real power of jQuery lies in the wrapper methods that operate on a set of
DOM
elements collected via the power of jQuery selectors. Next, let's see how we can
add our own powerful wrapper methods.
7.4 Adding new wrapper methods
The true power of jQuery lies in the ability to easily and quickly select and oper-
ate on
DOM
elements. Luckily, we can extend that power by adding wrapper
methods of our own that manipulate selected
DOM
elements as we deem appro-
priate. By adding wrapper methods, we automatically gain the use of the power-
ful jQuery selectors to pick and choose which elements are to be operated on
without having to do all the work ourselves.
Given what we know about JavaScript, we probably could have figured out on
our own how to add utility functions to the
$
namespace, but that's not true of
wrapper functions. There's a tidbit of jQuery-specific information that we need to
know; to add wrapper methods to jQuery, we must assign them as properties
to an object named
fn
in the
$
namespace.
The general pattern for creating a wrapper functions is
$.fn.wrapperFunctionName = function(params){function-body};
Let's concoct a trivial wrapper method to set the color of the matched
DOM
ele-
ments to blue.
(function($){
$.fn.makeItBlue = function() {
return this.css('color','blue');
}
})(jQuery);
As with utility functions, we make the declaration within an outer function that
guarantees that
$
is an alias to
jQuery
. But unlike utility functions, we create the
new wrapper method as a property of
$.fn
rather than of
$
.
NOTE
If you're familiar with object-oriented JavaScript and its prototype-based
class declarations, you might be interested to know that
$.fn
is merely an
alias for the
prototype
property of the
jQuery
constructor function.


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

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