jQuery in Action

jQuery fundamentals
13
Fortunately, and by design, jQuery makes it easy to extend its set of functions by
extending the wrapper returned when we call
$()
. Let's take a look at the basic
idiom for how that is accomplished:
$.fn.disable = function() {
return this.each(function() {
if (typeof this.disabled != "undefined") this.disabled = true;
});
}
A lot of new syntax is introduced here, but don't worry about it too much yet. It'll
be old hat by the time you make your way through the next few chapters; it's a
basic idiom that you'll use over and over again.
First,
$.fn.disable
means that we're extending the
$
wrapper with a function
called
disable
. Inside that function,
this
is the collection of wrapped
DOM
ele-
ments that are to be operated upon.
Then, the
each()
method of this wrapper is called to iterate over each element
in the wrapped collection. We'll be exploring this and similar methods in greater
detail in chapter 2. Inside of the iterator function passed to
each()
,
this
is a
pointer to the specific
DOM
element for the current iteration. Don't be confused
by the fact that
this
resolves to different objects within the nested functions. After
writing a few extended functions, it becomes natural to remember.
For each element, we check whether the element has a
disabled
attribute, and
if it does, set it to
true
. We return the results of the
each()
method (the wrapper)
so that our brand new
disable()
method will support chaining like many of the
native jQuery methods. We'll be able to write
$("form#myForm input.special").disable().addClass("moreSpecial");
From the point of view of our page code, it's as though our new
disable()
method was built into the library itself! This technique is so powerful that most
new jQuery users find themselves building small extensions to jQuery almost as
soon as they start to use the library.
Moreover, enterprising jQuery users have extended jQuery with sets of useful
functions that are known as plugins. We'll be talking more about extending jQuery
in this way, as well as introducing the official plugins that are freely available in
chapter 9.
Before we dive into using jQuery to bring life to our pages, you may be won-
dering if we're going to be able to use jQuery with Prototype or other libraries
that also use the
$
shortcut. The next section reveals the answer to this question.


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

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