DOM event model or DOM event mechanism

An event is an action performed by the user or the browser itself. It is an interaction between a document or the browser, such as a click button. Click is the name of the event. The interaction between JS and HTML is achieved through events, and DOM supports a large number of events.

Propagation after the occurrence of an event, propagation between child elements and parent elements will be divided into three stages.

  1. Looking for listeners from the outside in is called event capture
  2. Fires an event at the target node
  3. Looking for listeners from the inside out is called event bubbling

Event capture: When an event is triggered, the browser automatically checks for the same event from the top TAB outside the user’s action TAB. If so, the event is triggered. If not, the browser continues to check for the process of knowing the user’s action.

Event bubbling: The process in which the user continues to manipulate the label to check for the parent label, firing if the same event exists, and continuing to check up to the most parent element if not

The uppermost object of event propagation is window. The sequence of event propagation in the above example is window, Document, HTML, body, parent node, and target node in the capture stage, and target node, parent node, body, HTML, document, and Window in the bubble stage.

When both capture and bubble listen, capture first executes whichever div listens first, except when only one div is being listened on

Click on the event

<div class="grandfather">
  <div class="father">
    <div class="son">The text content</div>
  </div>
</div>

Copy the code
  1. When you click on the text content, who is clicked on?

    We can click on son, we can click on father, we can click on grandfather, they all count.

  2. Add event listener fnYe/fnBa/fnSon to three divs.

    Either, fnYe to fnBa to fnSon/fnSon to fnBa to fnYe. But because IE agrees with the latter and Netscape agrees with the former, the W3C publishes the standard.

    Specifies that browsers should support both call sequences

    Grandfather ->father->son

    Then follow son->father->grandfather

AddEventListener event binding API

IE5* : baba. AttachEvent (‘onclick’,fn)// bubbles

Netscape: baba.addeventListener (‘click’,fn)// capture

W3C: baba.addEventListener(‘click’,fn,bool)

When bool is true, FN is captured

Bool does not pass or falsy, FN goes bubbling

Target v.S. currentTarget

The currentTarget event attribute returns the node from which its listener triggered the event, that is, the element, document, or window that is currently processing the event.

The target event property returns the target node of the event (the node that triggered the event) that the user clicked.

The difference between:

This is e.currenttarget, and I personally don't recommend using itCopy the code

Such as:

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

Cancel bubbling (capture cannot be undone but bubbling can)

E.toppropagation () interrupts bubbles and is generally used to encapsulate some independent components

Event delegation

Event delegate: Delegate an element to listen for events THAT I should listen for (click events)

Custom events:

button1.addEventListener('click'.() = >{
  const event = new CustomEvent("cheng", {"detail": {name:'cheng'.age: 20}})
  button1.dispatchEvent(event)
})

button1.addEventListener('cheng'.(e) = >{
  console.log('cheng')
  console.log(e)
})
Copy the code

Add click events to 100 buttons:

div1.addEventListener('click'.(e) = >{
  const t = e.target
  if(t.tagName.toLowerCase()==='button') {console.log('Button is clicked')}})/ / toLowerCase lowercase

Copy the code

Listen for click events for elements that do not currently exist:

Listen for ancestors and wait to see if they are listening to the element when clicked.

setTimeout(() = >{
  const button = document.createElement('button')
  button.textContent='click 1'
  div1.appendChild(button)
},1000)

div1.addEventListener('click'.(e) = >{
  const t = e.target
  if(t.tagName.toLowerCase()==='button') {console.log('button is click')}})Copy the code

Encapsulate an event delegate

Method 1 (false but can be used in an interview) :

setTimeout(()=>{ const button = document.createElement('button') button.textContent='click 1' div1.appendChild(button) }, 1000) on (' click ', '# div1', 'button' () = > {/ / '# div elements is selector is not the console. The log (' button was clicked on the')}) function on(eventType,element,selector,fn){ if(! (element instanceof Element)){ element = document.querySelector(element) } element.addEventListener(eventType,(e)=>{ Const t= e.target {//matches an element to a match (a selector) {//matches an element to a match (a selector);Copy the code

Method 2:

 on: function(element, eventType, selector, fn) {
    element.addEventListener(eventType, e= > {
      let el = e.target
      while(! el.matches(selector)) {if (element === el) {
          el = null
          break
        }
        el = el.parentNode
      }
      el && fn.call(el, e, el)
    })
    return element
  },
Copy the code