04.11.2015 Views

javascript

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

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

Chapter 12: Events<br />

Safari 3 and Chrome have bugs that cause DOMNodeRemoved to be fired twice in a<br />

row on the same node.<br />

Node Insertion<br />

When a node is inserted into the DOM using appendChild() , replaceChild() , or insertBefore() ,<br />

the DOMNodeInserted event is fired first. The target of this event is the inserted node, and the<br />

event.relatedNode property contains a reference to the parent node. At the point that this event fires,<br />

the node has already been added to the new parent. This event bubbles, so the event can be handled at<br />

any level of the DOM.<br />

Next, the DOMNodeInsertedIntoDocument event fires on the newly inserted node. This event doesn ’ t<br />

bubble, so the event handler must be attached to the node before it is inserted. The target of this event is<br />

the inserted node, and the event object provides no additional information.<br />

The last event to fire is DOMSubtreeModified , which fires on the parent node of the newly<br />

inserted node.<br />

Considering the same HTML document used in the previous section, the following JavaScript code<br />

indicates the order of events:<br />

EventUtil.addHandler(window, “load”, function(event){<br />

var list = document.getElementById(“myList”);<br />

var item = document.createElement(“li”);<br />

item.appendChild(document.createTextNode(“Item 4”));<br />

EventUtil.addHandler(document, “DOMSubtreeModified”, function(event){<br />

alert(event.type);<br />

alert(event.target);<br />

});<br />

EventUtil.addHandler(document, “DOMNodeInserted”, function(event){<br />

alert(event.type);<br />

alert(event.target);<br />

alert(event.relatedNode);<br />

});<br />

EventUtil.addHandler(item, “DOMNodeInsertedIntoDocument”, function(event){<br />

alert(event.type);<br />

alert(event.target);<br />

});<br />

});<br />

list.appendChild(item);<br />

This code begins by creating a new < li > element containing the text “ Item 4 ” . The event handlers for<br />

DOMSubtreeModified and DOMNodeInserted are added to the document since those events bubble.<br />

Before the item is added to its parent, an event handler for DOMNodeInsertedIntoDocument is added<br />

to it. The last step is to use appendChild() to add the item, at which point the events begin to fire.<br />

The DOMNodeInserted event fires on the new < li > item, and the relatedNode is the < ul > element.<br />

Then DOMNodeInsertedIntoDocument is fired on the new < li > item, and lastly the<br />

DOMSubtreeModified event is fired on the < ul > element.<br />

405

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

Saved successfully!

Ooh no, something went wrong!