JS Event Listener英文笔记|青训营

122 阅读2分钟

前言

还有即将在国外投身秋招的小伙伴吗?本文是将课堂内容翻译成英文的笔记,加入了自己Google的内容。给将要在国外面试和在国内想学习英文的小伙伴们都做个参考~

Event Listener

  • obj.addEventListener("action", callback, {option})

  • "action" can be "click", "mouseover", etc.

  • Callback takes a single parameter, which is the event object

    • Callback is usually written as an arrow function e => {}
    • Event object has a lot of attributes, including target (which object you clicked), mouse position, etc.
    • Multiple event listeners on the same object will be executed in the sequence they are written
    • e.stopPropagation() will stop all capture & bubble phases behind this event
  • obj.removeEventListener("action", callback)

    • Note: to successfully remove an event listener, the callback must be the same function referred to in the addEventListener function. Aka, you cannot use arrow functions in two places, you must craete a named function for callback.
  • Option is an object with many attributes

    • {capture: true}: sets this event listener as a capture event. By default, this option is false, meaning the event listener is a bubble event
    • {once: true}: This event will only run once the first time it happens. If you perform the same action again, it will not happen again, but event propagation is not stopped
  • Phase 1: Event Capturing

    • Goes from top element to the innermost children
    • Will trigger all capture event listeners
  • Phase 2: Event Bubbling

    • Goes from closest child to the top element
    • An event heard by a child will be bubbled up to the very top of its parents (e.g. The document itself), because an event happening to a child (clicked on a button) also happened to its parents (aka, you clicked somewhere inside the document)
    • Will trigger all bubble event listeners
  • Event delegation

    • Sometimes JS adds dynamic elements to a page, aka creates new elements in runtime that was not present before. In this way, event listeners targeting original elements can not cover new elements. To solve this, we add a global (document-wide) event listener, and match the event target with the selector we want.
    • We can do this because we know all events eventually bubble up to the document itself.
    • function addGlobalEventListener(type, selector, callback, options) {
          document.addEventListener(type, 
          e => {  
            if (e.target.matches(selector)) callback(e)   
          },    
          options
         )
        }
        
      addGlobalEventListener( 
          "click",
          ".btn", 
          () => { console.log("Clicked Button") },
          { once: true }
       )
      

总结

本知识点绝对是面试必考,而且理解event listener会帮助大家学会控制冒泡,防止unintended behaviour。不清楚的话Inspector永远是最好的朋友~