JS event binding, event triggering, event object, event delegate, throttling and anti chattering

Posted by sarakmo on Wed, 05 Jan 2022 15:17:52 +0100

This is some basic content of JavaScript events previously sorted out.

1, The origin of the event

With the rapid development of the Web, the static page of HTML+CSS can no longer meet the needs of users, so there is JavaScript that allows users to interact with the browser, and the great hero to realize this function is what we are talking about this time - events. Event is the bridge of interaction between JavaScript and DOM. It refers to the operation performed by users due to some behavior on the browser.

  • Classification of events

UI events

  • load Web page loading complete
  • The unload Web page is unloading
  • error JS parsing error or nonexistent resources
  • resize browser window size change
  • Scroll scroll bar move

Keyboard events

  • keydown the user presses the key
  • keyup user releases key
  • keypress pressed a character

Mouse event

  • click press and release on an element
  • dblclick double clicks on an element and releases it
  • mousedown press the mouse button on an element
  • mouseup releases the mouse button on an element
  • mousemove mouse movement
  • mouseover mouse over an element
  • mouseout move the mouse away from an element

focal event

  • The focus / focus in element gets the focus
  • The blur/focusout element loses focus

Form Events

  • The value in the input field has changed
  • The value of the change form element has changed
  • submit user submits form
  • Cut cut the content
  • copy copied content
  • paste pastes the content

Change event

  • The domsubtree modified document has changed
  • DOMNodeInserted a node is inserted as a direct child node of another node
  • DOMNodeRemoved a node is removed from another node
  • DOMNodeInsertedIntoDocument a node is inserted as a descendant of another node
  • DOMNodeRemovedFromDocument a node is removed from its ancestor node

These various event types make JavaScript code very flexible and provide more possibilities for developers' design.

  • How to bind events to nodes

With the development of the times, there are not only more and more types of events, but also many binding methods between events and DOM nodes.

DOM level 0 events

<a onclick="alert()"></a>

This writing method can bind at the fastest speed without waiting for JS to run. However, due to the separation of HTML and JS code, most of the following forms are used to bind nodes and events in JS code.

element.onclick = function(){}

DOM0 events have an excellent cross browser advantage, that is, good compatibility.

DOM1 level events

There is no event related content defined in the level 1 DOM standard, so there is no so-called level 1 DOM event model.

DOM Level 2 events

element.addEventListener('click', myFunttion(obj), false)

The execution function passed in here cannot be parenthesized, otherwise the JS code will be considered to execute this function when it is executed here. If parameters are to be passed in, anonymous functions can be used, as follows:

element.addEventListener('click', function(){

myFunction(object);

}, false)

It is estimated that someone will ask. Although anonymous functions are easy to use, what should I do if I want to remove this event? We all know that node can be used to remove binding events Removeeventlistener ('type ', funName), but you need to specify the event type and the bound function name, but the anonymous function has no name. In this case, you can remove the event by using the following methods:

var fun;

btn.addEventListener("click",function(e){

fun=arguments.callee; //arguments.callee refers to this function

});

function remove(){

btn.removeEventListener("click",fun);

}

DOM3

  • Event flow

Because HTML elements are always box by box, when you trigger a click event in a child element, it is also equivalent to clicking on a parent element. If both parents and children have bound click events, the sequential triggering of events will generate an event flow. Event flow has two different flows: event bubbling and event capture.

 

 

Event Bubbling

Concept: events propagate from the most specific node to the top-level node (window). This is the default type of event flow and is also supported by most browsers. Not all events can bubble, such as blur, focus, load, unload, etc.

Event capture

Concept: events propagate inward from the top-level (window) node to the most specific node, which is not supported in IE8 and below.

Add event bubbling and event capture execution order on multiple nodes at the same time

See the results of the experiment:

grandfather.addEventListener('click',function(){

            console.log('Master node capture');

        },true)

        father.addEventListener('click',function(){

            console.log('Parent node bubbling');

        },false)

        son.addEventListener('click',function () {

            console.log('Bubbling of seeds');

        },false)

        son.addEventListener('click',function () {

            console.log('Sub capture');

        },true)

Click the child node:

 

grandfather.addEventListener('click', function () {

            console.log('Master node capture');

        }, true)

        father.addEventListener('click', function () {

            console.log('Parent node bubbling');

        }, false)

        son.addEventListener('click', function () {

            console.log('Sub capture');

        }, true)

        son.addEventListener('click', function () {

            console.log('Bubbling of seeds');

        }, false)

Click the child node:

 

Conclusion: the events bound to click elements occur in the order of the code, and other unbound elements are triggered by bubbling or capturing. According to the W3C standard, the capture event occurs first and then the bubble event occurs. Therefore, the overall sequence of events is: non target element capture - > target element code sequence - > non target element bubble.

  • Event object

Whenever an event occurs, if there is a specified parameter, the event object will be passed in as the first parameter of the anonymous encapsulation function (occurs automatically). The event object contains some useful information and methods of the event.

function hide(e,object){

e.target /srcElement(IE8 following) //Object of the event

e.type //Type of event

e.preventDefault(); //Block default events such as hyperlink jumps

e.stopPropagation(); //Prevent event bubbling / capture

event.stoplmmediatePropagation() //Block not only the default event, but also the event flow

......

}

var a=document.getElementById('a');

a.addEventListener('click',function(e){

hide(e,obj);

},false);

Event delegation

When there are too many child elements, adding listeners one by one will reduce the page fluency, so use the characteristics of event flow to delegate the work of event listeners to parent elements or ancestor elements.

Example: each < li > click of a < UL > can pop-up. If there are 1000 < li > in < UL >, we can only bind a click event trigger pop-up on < UL >, instead of adding events to < li > one by one.

Event throttling

High frequency events are triggered, but they will only be executed once in n seconds. Each time an event is triggered, if there is a delay function waiting to be executed, return directly.

function throttle(fn,delay=100){
    let timer=null    
    return function(){
        if(timer){
            return
        }
        time=setTimeout(()=>{
            fn.apply(this,arguments)
            timer=null
        },delay)lay)
    }
}

Event anti shake

After triggering the high-frequency event, the function will be executed only once in n seconds. If the high-frequency event is triggered again in n seconds, the time will be recalculated. If the event is continuously triggered within a specified time interval, the calling method will be continuously delayed.

function debounce(fn,delay=500){
    let timer=null
    return function(){
        if(timer){
            clearTimeout(timer)
        }
        timer=setTimeout(()=>{
            fm.apply(this,arguments)
            timer=null
        },delay)
    }
}

Topics: Javascript Front-end