23.04.2013 Views

javascript

javascript

javascript

SHOW MORE
SHOW LESS

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

CHAPTER 9 ■ LISTENING FOR EVENTS<br />

function thwart(e) {<br />

if (e.preventDefault) {<br />

thwart = function(e) {<br />

e.preventDefault();<br />

};<br />

} else {<br />

thwart = function(e) {<br />

e.returnValue = false;<br />

};<br />

}<br />

thwart(e);<br />

}<br />

The first time thwart() runs, it does a lot of work. But thereafter, thwart() runs snappily since its<br />

block contains but one statement. In Internet Explorer 9, Firefox, Safari, Chrome, and Opera, that would<br />

be e.preventDefault(), and in Internet Explorer or earlier that would be e.returnValue = false.<br />

Preventing an Event from Traversing the DOM Tree<br />

Now then, in Internet Explorer 9, Firefox, Safari, Chrome, and Opera, an event object descends the DOM<br />

tree to the element an event happened on. Then turns tail and ascends the DOM tree. So, the event<br />

object passes by any ancestor of the target of the event two times. On the other hand, in Internet<br />

Explorer 8 or earlier, the event object passes by any ancestor one time, that is, while bubbling upward<br />

through the DOM tree. Therefore, if you register event listeners for a certain kind of event, say a click, on<br />

nodes that are on different tiers of the DOM tree, all of those could potentially run when a click event<br />

occurs.<br />

There ought to be a way to prevent an event object from traversing any further through the DOM<br />

tree to avoid triggering additional event listeners, right? And there is. Just as with preventing default<br />

actions, you do so by calling a method for Internet Explorer 9, Firefox, Safari, Chrome, and Opera and by<br />

writing a member for Internet Explorer 8 or earlier. The DOM method is named stopPropagation(), and<br />

the Internet Explorer 8 or earlier member is named cancelBubble. Note that Internet Explorer 9 and<br />

Opera implement both stopPropagation() and cancelBubble. With this in mind, we can write a lazy<br />

loader to do the job by changing some identifiers in thwart().<br />

Now cut and paste thwart(). Then change the identifier thwart to burst in four places:<br />

function burst(e) {<br />

if (e.preventDefault) {<br />

burst = function(e) {<br />

e.preventDefault();<br />

};<br />

} else {<br />

burst = function(e) {<br />

e.returnValue = false;<br />

};<br />

}<br />

burst(e);<br />

}<br />

Next, change the identifier for the DOM method from preventDefault to stopPropagation in two<br />

places:<br />

function burst(e) {<br />

if (e.stopPropagation) {<br />

355

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!