Home > Web Front-end > JS Tutorial > body text

js event stream and extended application examples

小云云
Release: 2018-03-26 17:34:45
Original
1385 people have browsed it

What is event flow? This article mainly shares with you js event flow and extended application examples, hoping to help everyone.

js event stream and extended application examples
The DOM standard stipulates that the event flow includes three stages: the event capture stage, the target stage and the event bubbling stage.
● Event capture phase: The actual target (<p></p>) will not receive events during the capture phase. That is, during the capture phase, the event stops from document to and then to . In the picture above, it is 1~3.
● In the target stage: The event occurs and is processed on <p></p>. But event handling is considered part of the bubbling phase.
● Bubbling stage: The event propagates back to the document.
note:
1). Although the "DOM2-level event" standard specification clearly stipulates that the event capture phase will not involve event targets, but in IE9, Safari, Chrome, Firefox and Opera9.5 and higher versions, they will be captured during the capture phase. The stage triggers events on the event object. As a result, there are two opportunities to operate events on the target object.
2), not all events will go through the bubbling stage. All events must go through the capture phase and be in the target phase, but some events will skip the bubbling phase: for example, the focus event that gains input focus and the blur event that loses input focus.

Capture event flow: The propagation of events is from the least specific event target to the most specific event target. That is, from the root of the DOM tree to the leaves.
Bubble event flow: The propagation of events is from the most specific event target to the least specific event target. That is, from the leaves of the DOM tree to the root.

Then what is to be implemented here is the bubbling event flow, from the inside (leaf) to the outside (root)

//只需要在window.onload里面给每一个圆添加点击事件处理程序就ok了哦,其余代码请看上[一篇文章](https://blog.csdn.net/weixin_38323736/article/details/79685589)当然是在圆画好之后执行这一段代码,所以位置放在后面,别放错var circles=document.getElementsByClassName("circle");    for(var i=0;i<n;i++){
        circles[i].onclick=function(e){

            //currentTarget表示当前处理该事件的元素、文档或窗口,childNodes是子节点的意思,这里遍历子节点
            e.currentTarget.childNodes.forEach(function(v) {

                //把文本节点找出,不然html代码也会输出的
                if(v instanceof Text) {                    //文字节点为Text()实例,用data或者wholeText可以取到String类型的文本
                    //解决方法参照:https://segmentfault.com/q/1010000009913772/a-1020000009914008
                    console.log(v.data);                    // console.log(v.wholeText);
                }
            });
        }
    }
Copy after login

ok, it’s that simple.
Students who are eager to learn will definitely want to see the event capture. Let me write out both types so that everyone can see what the entire event flow looks like.

circles[i].onclick =function(e){}This writing method is dom0 level writing method. You can only write one event. Writing another one will overwrite it, and it only supports bubbling events.
addEventListener is different. , it can write multiple events and will not overwrite

//这段代码包含了上面的js代码哦var circles=document.getElementsByClassName("circle");for(var i=0;i<n;i++){
    circles[i].addEventListener("click",function(e){
        e.currentTarget.childNodes.forEach(function(v) {
            if(v instanceof Text) {
                console.log(v.data+" 捕获阶段");
            }
        });        //true表示事件句柄在捕获阶段执行; 
        //false- 默认。事件句柄在冒泡阶段执行
    },true);            
    circles[i].addEventListener("click",function(e){
        e.currentTarget.childNodes.forEach(function(v) {
            if(v instanceof Text) {
                console.log(v.data+" 冒泡阶段");
            }
        });
    },false);
}
Copy after login

At this time, click 15, the following effect will appear
js event stream and extended application examples

ok, in fact, the event bubbles There is a good application, that is, event proxy

Event proxyThat is, Event delegation

In traditional event processing, it is necessary to Add an event handler to an element. js event proxy is a simple and effective technique through which you can add event handlers to a parent element, thereby avoiding adding event handlers to multiple child elements.

The principle of event proxy uses event bubbling and target elements. Add the event handler to the parent element, wait for the child element event to bubble up, and the parent element can determine whether it is through the target (IE is srcElement) Which sub-element, so as to handle it accordingly.

Benefits of event proxy
● Reduce multiple event handlers to one, because event handlers need to reside in memory, which improves performance. Imagine that there is a table with 100 rows. Compared with the traditional way of binding event handlers to each cell and the event proxy (that is, adding an event handler to the table), it is not difficult to conclude that the event proxy does avoid some potential risk and improved performance.
● DOM updates do not require rebinding event handlers, because event proxies can use different processing methods for different sub-elements. If you add other sub-elements (a, span, p, etc.), you can directly modify the event processing function of the event proxy. There is no need to rebind the processor or loop through again.

For example, now I want to output 15 when clicking the circle of 15. We first use the traditional loop method to write, and then use the event delegation method to write

var circles=document.getElementsByClassName("circle");for(var i=0;i<n;i++){
    circles[i].addEventListener("click",function(e){
        e.currentTarget.childNodes.forEach(function(v) {
            if(v instanceof Text) {
                console.log(v.data);
            }
        });        //阻止冒泡哦!!!不然不止输出15了
        e.stopPropagation();
    },false);
}
Copy after login

This kind of In fact, the method consumes performance. It will be written several times during compilation if it is looped several times. Therefore, it is not as good as the event proxy. It only needs to be written once:

//获取外面的大圆,只需要交给大圆来处理就okvar circle=document.getElementById("circle");
circle.addEventListener("click",function(e){
    e=e||window.event;    var targetElement=e.target||e.srcElement;
    targetElement.childNodes.forEach(function(v) {
        if(v instanceof Text) {
            console.log(v.data);
        }
    });
})
Copy after login

Haha, does anyone want to ask, so what is used above? Multi-loop, why not also use event proxy to write it? I thought about it, and I really can write it

var circle=document.getElementById("circle");
circle.addEventListener("click",function(e){
       e=e||window.event;       var targetElement=e.target||e.srcElement;       while(targetElement.nodeName!="BODY"){
        targetElement.childNodes.forEach(function(v) {
            if(v instanceof Text) {
                console.log(v.data);
            }
        });
        targetElement=targetElement.parentNode;
    }
},false)
Copy after login

Related recommendations:

Detailed explanation of DOM event flow of js

JavaScript event learning Summary of event streams, handlers and objects

What is JavaScript event stream and event handler detailed explanation

The above is the detailed content of js event stream and extended application examples. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!