Partilhar via


Event capture and bubbling with DOM events

[This article is for Windows 8.x and Windows Phone 8.x developers writing Windows Runtime apps. If you’re developing for Windows 10, see the latest documentation]

In Windows Library for JavaScript there are several addEventListener methods (for example, WinJS.Application.addEventListener and WinJS.UI.AppBar.addEventListener). They all contain a useCapture parameter, which is set to true if you want event capture or false if you want event bubbling. For more information, see Event capture and Event bubbling.

In the addEventListener method, if you set the useCapture parameter to true, the order in which events are handled is top-down. That is, if there are event handlers for the specified event that belong to more than one element in the DOM tree, the handler belonging to the highest element in the tree is called first, and any handlers belonging to child elements are called after that. If you set the useCapture parameter to false, the handler that belongs to the target element is called first, and any handlers that belong to parent elements are called after that.

In this example, you create a WinJS.UI.ToggleSwitch and add the same change handler function to the WinJS.UI.ToggleSwitch and the document object. If you set the useCapture parameter to true, the handler on the document object is called first, then the handler on the WinJS.UI.ToggleSwitch object.

In an event, the this keyword refers to the target of the event, so you should see "change event for [object HTMLDocument]" and then "change event for [object HTMLDivElement]". If you set the useCapture parameter to false, you should see the output for the DatePicker handler first, then the output for the document handler.

HTML for toggle control host and output

<div id="div"></div>
<div id="report"></div>

JavaScript to add event handlers


var toggle = new WinJS.UI.ToggleSwitch(document.getElementById("div"));

toggle.addEventListener("change", handleChange, true);
document.addEventListener("change", handleChange, true);

function handleChange(ev) {
    var elem = document.getElementById("report");
    elem.innerHTML += 
       toStaticHTML("<br> change event for " + this);
}