jQuery in Action

92
CHAPTER 4
Events are where it happens!
at a time. If we have two things that we want to do when an element is clicked, the
following statements aren't going to let that happen:
someElement.onclick = doFirstThing;
someElement.onclick = doSecondThing;
Because the second assignment replaces the previous value of the
onclick
prop-
erty, only
doSecondThing
is invoked when the event is triggered. Sure, we could
wrap both functions in another single function that calls both; but as pages get
more complicated, as is highly likely in Rich Internet Applications, it becomes
increasingly difficult to keep track of such things. Moreover, if we use multiple
reusable components or libraries in a page, they may have no idea of the event-
handling needs of the other components.
We could employ other solutions: implementing the Observable pattern that
establishes a publish/subscribe scheme for the handlers, or even tricks using clo-
sures. But all of these add complexity to pages that are already complex enough.
Besides the establishment of a standard event model, the
DOM
Level 2 Event
Model was designed to address these types of problems. Let's see how event han-
dlers, even multiple handlers, are established on
DOM
elements under this more
advanced model.
Establishing events
Rather than assigning a function reference to an element property,
DOM
Level 2
event handlers--also termed listeners--are established via an element method.
Each
DOM
element defines a method named
addEventListener()
that's used to
attach event handlers (listeners) to the element. The format of this method is
as follows:
addEventListener(eventType,listener,useCapture)
The
eventType
parameter is a string that identifies the type of event to be han-
dled. This string is, generally, the same event names we used in the
DOM
Level 0
Event Model without the on prefix: for example, click, mouseover, keydown, and
so on.
The
listener
parameter is a reference to the function (or inline function)
that's to be established as the handler for the named event type on the element.
As in the basic event model, the
Event
instance is passed to this function as its
first parameter.
The final parameter,
useCapture
, is a Boolean whose operation we'll explore
in a few moments when we discuss event propagation in the Level 2 Model. For
now, leave it set to
false
.


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

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