Home >Web Front-end >JS Tutorial >What is JavaScript event stream and event handler explained in detail

What is JavaScript event stream and event handler explained in detail

伊谢尔伦
伊谢尔伦Original
2017-07-24 15:42:502044browse

The interaction between JS and HTML is achieved through events. Events are specific moments of interaction that occur within a document or browser window. You can use listeners (or handlers) to schedule events so that appropriate code is executed when the event occurs. Known as the Observer pattern in traditional software engineering, this supports loose coupling between the behavior of the page and the appearance of the page.

Event flow

Event flow describes the order in which events are received from the page.

Event bubbling

The event is initially received by the most specific element (the node with the deepest nesting level in the document), and then Levels are propagated upward to less specific nodes (documents). Take the following HTML page as an example. If you click a button on the page, the "click" event will be propagated in the order of 37a9605a910bf1fbe848fe3f47ab78d9, 1d6e7d87652dd104f173dbf7284e2799, 07e6e06e0dc95dc83bb70d14dca11cbe, and document. In other words, event bubbling means that the event propagates upward along the DOM tree from the underlying element that triggered the event to the document object.


<html>
 <head>
  <title>Test</title>
 </head>
 <body>
  <button id="myBtn">A Btn</button>
 </body>
</html>

Event capture

Contrary to the idea of ​​event bubbling, the idea of ​​event capture is not Nodes that are too specific should receive events earlier, and nodes that are most specific should receive events last. Still in the above example, after clicking the button on the page, the "click" event will be propagated in the order of document, 07e6e06e0dc95dc83bb70d14dca11cbe, 1d6e7d87652dd104f173dbf7284e2799, 37a9605a910bf1fbe848fe3f47ab78d9. In other words, event capture means that the event propagates downwards along the DOM tree from the document object until the actual target element of the event.

DOM event flow

The events specified by "DOM2-level events" include three stages: event capture stage, target stage and event risk bubble stage. The first thing that happens is event capture, which provides the opportunity to intercept the event. Then the actual target receives the event. The final phase is the bubbling phase, where you can respond to events.

Still taking the previous click button as an example, in the DOM event flow, during the capture phase, the "click" event is passed from the document down to the body element (note that the actual target button will not receive it during the capture phase event). In the target phase, the button element receives the "click" event. Finally, in the bubbling phase, the event is propagated back to the document.

Event handler

An event is a certain action performed by the user or the browser itself, and the function that responds to an event is called an event handler or event listener device.

HTML event handler

The HTML event handler here refers to the event defined directly in the HTML element through attributes. handler, see the code example below. In this case, the event handler will create a function that encapsulates the element's attribute value, and this value is equal to the target element of the event. Specifying event handlers in this way has several disadvantages and is not recommended.


<button onclick="alert(&#39;HaHa~&#39;)">Btn-1</button>
<button onclick="alert(&#39;event.type&#39;)">Btn-2</button>
<button onclick="handler()">Btn-3</button>
<script type="text/javascript">
 function handler() {
  alert("Haha~");
 }
</script>

DOM Level 0 Event Handler

The traditional way to specify an event handler through JS is to A function is assigned to an event handler property, see the code example below. Event handlers specified this way run within the scope of the element, with this referring to the current element. Event handlers added in this way will be processed during the bubbling phase of the event flow. If you want to delete the event, just set the value of onclick to empty.


var btn = document.getElementById("myBtn");
btn.onclick = function() {
 console.log("this.id"); // "myBtn"
};
// 删除事件处理程序
btn.onclick = null;

DOM2-level event handler

"DOM2-level event" defines two methods with For specifying and removing event handlers, addEventListener() and removeEventListener(). These two methods are included in all DOM nodes. Both methods receive 3 parameters, the event to be processed, the processing function, and the Boolean value. The final Boolean value means that the event handler is called during the capture phase when true, and false when the event handler is called during the bubbling phase. Like the DOM0-level methods, the event handler added here also runs in the scope of the element to which it is attached. The advantage of adding event handlers using the DOM2-level method is that you can add multiple event handlers. These event handlers are fired in the order they were added. The following is a code example:


var btn = document.getElementById("myBtn");
// 添加,触发点击事件时先输出"myBtn"再输出"HaHa~"
btn.addEventListener("click", function() {
 console.log(this.id);
}, false);
btn.addEventListener("click", function() {
 console.log("HaHa~");
}, false);

Events added through addEventListener() can only be removed through removeEventListener(). The parameters passed in when deleting should be consistent with the parameters used when adding. This also means that the anonymous function added through addEventListener() cannot be deleted, because the anonymous function passed when adding cannot be passed to removeEventListener(). Even if an identical function is written when deleting, this function is just a New anonymous function. Please see the following code example:


var btn = document.getElementById("myBtn");
// 无法删除匿名函数
btn.addEventListener("click", function() {
 console.log(this.id);
}, false);
btn.removeEventListener("click", function() {
 console.log(this.id);
}, false);

// 正确的添加和删除方式
function handler() {
 console.log(this.id);
}
btn.addEventListener("click", handler, false);
btn.removeEventListener("click", handler, false);

大多数情况下,都是将事件处理程序添加到事件流的冒泡阶段,这样可以最大限度地兼容各种浏览器。最好只在需要在事件到达目标之前截获它的时候才将事件处理程序添加到捕获阶段。JS高级程序设计上给出的建议是,如果不是特别需要,不建议在事件捕获阶段注册事件处理程序。

IE事件处理程序

IE实现了与DOM中类似的两个方法: attachEvent()和deleteEvent()。这两个方法接收两个参数,事件处理程序名称和事件处理程序。注意,第一个参数是事件处理程序名称而不是事件名称,也就是说在注册点击事件的处理程序时应该传入”onclick”而不是”click”,这里跟DOM的方法有些差别。另外,这两个方法注册的事件处理程序是在全局作用域中运行而不是元素作用域,this的值指向window。还有一点需要特别小心,通过attachEvent()方法也可以添加多个事件处理程序,但是它们的执行顺序却不是按照它们被添加的顺序,而是完全相反,跟DOM方法截然不同。突然觉得IE真的特别反人类~~~下面是代码示例:


var btn = document.getElementById("myBtn");
function handler1() { // ... }
function handler2() { // ... }
// 添加,触发点击事件时先执行handler2再执行handler1
btn.attachEvent("onclick", handler1);
btn.attachEvent("onclick", handler2);
// 删除
btn.deleteEvent("onclick", handler1);
btn.deleteEvent("onclick", handler2);

The above is the detailed content of What is JavaScript event stream and event handler explained in detail. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn