Web Development with jQuery®

(Elliott) #1

Attaching Persistent Event Handlers (^) ❘ 69
method that you’d use in JavaScript if you weren’t working with a JavaScript framework. It simply
has more features built into it to make working with events a lot easier.
Instead of $('div.finderDirectory, div.finderFile').click(), you use $('div.finderDirectory,
div.finderFile').on('click'). Finally, to trigger an event to be fi red, instead of just calling the
event method, like click(), you call the trigger() method with the event name as its argument,
such as, trigger('click').


Attaching Persistent Event Handlers


A convenient and cool feature of jQuery’s on() and off() methods is the concept of attaching events
to nodes in the DOM that might not even exist when you create the event handler. Internally, this
feature works by attaching an event to a node that is higher up the DOM tree and thus does exist at
the time the event handler is processed and attached.

For example, you might attach a click event to the document object. Then, by providing a selector
to the second argument of the on() method, you create a persistent event handler that applies to
only the nodes described by the selector. Those nodes described by the selector can exist or not exist
at the time the event handler is created; the only catch is the nodes must exist inside the object the
event handler is attached to.

Then using event propagation, the event takes place and bubbles up the DOM tree to the element
the event handler is attached to. jQuery continuously looks at the event.target property to see if the
node that received the event is described by the selector that you provide. If it is, then it applies the
event handler.

The following example, which can be found in the source materials as Example 3-3, takes the
previous two examples and implements the concept of persistent events. (jQuery’s documentation
has also referred to this concept as live events.) You begin with modifying the HTML so that some
fi les can be added after the event handler is created.

<!DOCTYPE HTML>
<html lang='en'>
<head>
<meta http-equiv='X-UA-Compatible' content='IE=Edge' />
<meta charset='utf-8' />
<title>Finder</title>
<script src='../jQuery.js'></script>
<script src='../jQueryUI.js'></script>
<script src='Example 3-3.js'></script>
<link href='Example 3-3.css' rel='stylesheet' />
</head>
<body>
<div id='finderFiles'>
<div class='finderDirectory finderNode' data-path='/Applications'>
<div class='finderIcon'></div>
<div class='finderDirectoryName'>
<span>Applications</span>
</div>
</div>
<div class='finderDirectory finderNode' data-path='/Library'>

http://www.it-ebooks.info

Free download pdf