First, several basic definitions of events

1. What is an event?

Browsers give elements some natural default behavior, regardless of whether the associated method is bound, whenever the behavior is performed, the associated event behavior must be triggered.

2. What is event binding?

Bind a method to an element’s event behavior so that the behavior trigger can do whatever it wants.

3. Bind DOM0 and DOM2 events

1. DOM0 event binding

Elements. Onxxx =function(){} element. Onxxx =null;
Copy the code
  1. Principle: Assign a function value to a private event attribute of the DOM element object. When the user triggers the event behavior, the JS engine will help us execute the previously bound method
    • Not all event types support this approach. What onXXX event attributes do elements have to bind methods to (e.g., DOMContentLoaded events do not support this binding scheme)
    • Only one method can be bound to the current element’s event behavior (multiple bindings can identify only the last one)

2. DOM2 Event binding

    / / bindingAddEventListener ([event type],[method],[propagation mode])/ / removeRemoveEventListener ([event type],[method],[propagation mode])// To make it easier to remove, write the function outside
    function anonymous(){
                    console.log('ok');
            }
    box.addEventListener('click',anonymous,false);
    box.removeEventListener('click',anonymous,false);
Copy the code
  1. AddEventListener (EventTarget. Prototype) is an eventpool-based event binding method

Event pool

AddEventListeener: Continuously adds content to the event pool)

DOM0 and DOM2 are bound

They don’t interact because they’re two different mechanisms

4. Event objects

  1. The event behavior of the current element is triggered, which not only executes the bound method, but also passes an argument to the bound method, which is the event object.
  2. An event object is an object that stores information about the current action. (MosueEvent/KeyboardEvent/Event/TouchEvent…).
  3. The => event object does not matter which method is retrieved, it records information about the current operation.

DOM event model and event delegate

DOM event model

Let’s take a look at some code

 <div class="Grandpa">
        <div class="Dad">
            <div class="Son">The text</div>
        </div>
</div>
Copy the code

Add event listener fnYe/fnBa/fnEr to each div. There are two problems:

Question 1: Who did you click on?

Click on the text, calculate not click son?

Click on the text, does that count as clicking dad?

Click text, does it count as click grandpa?

Answer: Both

2. Question 2: Call sequence

Click on the text and which function in fnYe/fnBa/fnEr is called first?

Answer: Either. The call sequence of IE5 is fnEr->fnBa->fnYe, and that of Netscape is fnYe->fnBa->fnEr.

In 2002, the W3C published a standard stating that browsers support both call sequences. See if there are functions listening in the order of grandpa -> Dad -> son, then see if there are functions listening in the order of son -> Dad -> Grandfather.

The technical terms are event capture and event bubbling for the DOM event model. Propagation between child elements and parent elements after an event occurs.

Event propagation mechanism

Event propagation mechanism: capture node – target phase – bubble phase

window-> document -> HTML ->body -> outer -> inner -> center

  • When an element receives an event, it receives itThe eventTo their parents, all the way up towindow
  • Of course, it propagates events, and the execution function of the binding does not propagate. If the parent has no binding event function, it will not behave if the event passes, but the event does pass.
  1. So the DOM event model is divided into three phases:

(1) Capture phase: the phase in which the event propagates from the Window object down to the target node (simplified to grandpa -> Dad -> son in the example code);

Look from the outermost container all the way up to the source of the currently emitted event. The purpose of lookups is to establish a path for future bubbling propagation of the current element.Copy the code

(2) Target stage: the stage when the real target node is processing events; (In sample code: text)

Trigger events related to the current element (bind method, execute method)Copy the code

(3) Bubble stage: the stage in which the event propagates from the target node to the Window object bottom-up (simplified to: son -> Dad -> Grandpa in the example code).

1. Not only the event behavior of the current element will be triggered, but also the event behavior of each element in the propagation path acquired in the recapture stage will be triggered [from inside out] 2. That is, all events related to the parent element will be raised. 3. If the corresponding method is also bound, the method will also be raised.Copy the code

Capture and bubble

Looking for listeners from the outside in is called event capture.

Looking for listener functions from inside out is called event bubbling.

Bind event API

DOM0

Bound methods are executed in the target or bubble phase.

DOM2 addEventListener (events)

You can control execution during the capture phase

IE5*: div1.attachevent ('onclick',fn)// Bubble Netscape: div1.addeventListener ('click',fn)// capture W3C:div1.addEventListener('click',fn,bool)Copy the code

If bool is not passed or falsy

Let fn bubble, that is, when the browser discovers that BABA has fn listeners during the bubbling phase, fn is called and the time information is provided.

If bool is true

Let go fncaptureWhen the browser is inCapture phaseIf you find that baba has fn listeners, you call FN and provide event information.

document.body.onclick =(ev)=>{ console.log("body",ev) } outer.onclick =(ev)=>{ console.log("outer",ev) } inner.onclick Onclick =(ev)=>{console.log("inner",ev)} center.onclick =(ev)=>{console.log("center",ev) } q: Are the four evs the same? Answer: It is the same. It does not matter which method the event object is in. The event object is used to record the information related to the current operation, that is, the operation is recorded once. No matter where the EV is obtained at this time, the information is recorded. Unless the operation is repeated, the last information is lost, and the EV stores the latest operation information.Copy the code
  1. When you click center in the middle, print center=>inner=>outer=> Body
  2. To prevent bubbling, just print Center

Demo code link

Code interpretation

code

E. target and E. Currenttarget

  1. The difference between:

This is e.currenttarget, and I personally don’t recommend using it

  1. For example:

Div >span{text}, the user clicks on the text e.target to span e.currenttarget to div

A special case of listening order

  1. background

Only one div is listened on (regardless of parent and child being listened on at the same time). Fn listens for click events in the capture phase and the bubble phase respectively

  1. code
div.addEventListenter('click',f1)

div.addEventListenter('click',f2,true)
Copy the code

Will F1 or F2 be executed first? What if I switch the two? 3. Answer: Who listens first who executes first.

Cancel bubbling and block default events

1. Cancel bubbling

Capture cannot be cancelled, but bubbling can

  1. Event.stoppropagation () can interrupt bubbling and the browser will no longer go up.

W3C standard Event.StopPropagation (); IE9 below is not supported.

Event. CancelBubble = true;

Function stopBubble(e) {if(e &&e.topPropagation) {// IE e.topPropagation (); } else { //IE window.event.cancelBubble = true; }}Copy the code
  1. Generally used to encapsulate some independent components
  2. Bubbles — Whether the event Bubbles, all Bubbles can be cancelled
  3. Cancelable — Whether developers are supported to block default events
  • Not all events can bubble up. The following events do not bubble:blur,focus,load,unload.
  • The event resolution may vary from browser to browser. Some do not support the capture solution, while most browsers default to the bubble solution.
  • Preventing bubbling does not prevent object default behavior, for examplesubmitWhen the button is clicked, it will submit the form datae.preventDefault();Prevent default behavior,IEIt iswindow.event.returnValue = false;.

2. Prevent default events

  1. Default events – form submission, A TAB jump, right-click menu, etc
  2. Methods:
Return false; Event.preventdefault ()W3C guideline: Event. ReturnValue = false; Compatible with IECopy the code
<a href="http://baidu.com/" id="testA" >baidu.com</a> var a = document.getelementbyid ("testA"); a.onclick =function(e){ if(e.preventDefault){ e.preventDefault(); }else{ window.event.returnValue == false; }}Copy the code

3. Event delegation

Custom events

  1. Browser custom events. MDN list.
  2. Custom events: Example

Event delegation

The “event broker” is the response event that needs to be bound to a child element (click, keydown……) Delegate to the parent element to take on the role of event listener. Event broker works by bubbling events from DOM elements

Refer to an article

Application scenarios

  1. Scenario 1:

How to add click events to 100 buttons?

A: Listen for the ancestor of the 100 buttons and wait for the bubble to determine if target is one of the 100 buttons

code

  1. Scenario 2:

You want to listen for click events for elements that don’t currently exist?

A: Listen for ancestors, wait until click to see if it is listening to the element.

code

advantages

  1. Save on listening (memory) : You can save a lot of memory and reduce event registration, such as proxying all li’s click events on UL is great.
  2. Elements can be listened on the fly: when a child object is added, it does not need to be bound again (dynamically bound events)

Encapsulate an event delegate

  1. Implement a function on(‘click’,’#testDiv’,’li’,fn) that can implement event delegation. The fn function is called when the user clicks the li element inside #testDiv.
  2. code