Web Development with jQuery®

(Elliott) #1

Removing Event Handlers (^) ❘ 75
addedAdditionalFiles = true;
}
);
First, you check the variable addedAdditionalFiles; if that variable is true, then execution of the
dblclick handler returns. If addedAdditionalFiles is false, then you look inside the

with the
id name finderAdditionalFiles for some extra
elements with class names finderFile, and
each of those are added to the other
element with the id name finderFiles.
When you click one of the new
elements, you notice that selection happens without any addi-
tional effort. This is what it means to use a persistent event handler; the event continues to work
when new elements are added that match the selector argument. Still using the fi le manager meta-
phor, this makes it possible to attach just one event handler for many fi les or folders, instead of an
event handler for each fi le and folder. If you have a lot of fi les and folders in the DOM, this also has
the advantage of substantially increasing performance. So, persistent event handlers benefi t you in
two key ways.



  1. The element does not have to exist when the event handler is created. The element can be
    created later; it just has to match the selector that you provide to the on() method.

  2. Client-side browser performance can be substantially boosted because you can reduce the
    number of event handlers that you need for a given event to just one from potentially many.


Removing Event Handlers


The on() method has a companion method called off(), which removes event handlers from a docu-
ment. jQuery also provides a useful way of discerning which events should be removed by virtue of
its capability to namespace event handlers.

Within a more complicated client-side application, you can quickly lose track of which scripts create
which event handlers. This is easily remedied by the introduction of named events by jQuery.

The syntax used to name an event is simple: In the argument where you name the event, you add a
dot and then the name that you want to use. The syntax works similarly to class names. And like
class names, using multiple dots will allow you to refer to multiple names. And referring to any one
name refers to any event using that name (even if that event has multiple names attached to it).

The following example, which can be found in the source materials as Example 3-4, demonstrates
how to work with named events, as well as how to dynamically apply and remove an event handler.
You begin with the same HTML that you worked with in preceding examples; you add two new
buttons to dynamically apply and remove events.

<!DOCTYPE HTML>
<html lang='en'>
<head>
<meta http-equiv='X-UA-Compatible' content='IE=Edge' />
<meta charset='utf-8' />
<title>Finder</title>

http://www.it-ebooks.info