Pay attention to “songbao write code”, selected good articles, a question of the day

Saucxs | songEagle

2020, real “rat” is not easy

In 2021, “niu” changes the world

When the wind is strong and the tide is surging, the heavy task must be bravely hoof!

One, foreword

This topic covers JavaScript, Node, Vue, React, browser, HTTP, etc.

Q: What is the understanding of event flow, event handler and event object in JS?

This is a very broad question, how to answer the highlight?

Yesterday’s question number is wrong, here is an explanation.

Second, the directory

  • Flow of events
  • Event handler
    • HTML event handler
    • DOM0 level event handler
    • Dom2-level event handler
    • IE event handler
    • Implement event handlers across browsers
  • Event object
    • Event objects in the DOM
    • Event objects in IE
    • Cross-browser event objects

1. Event flow

The event flow describes the order in which events are received from the page.

Event bubbling flow

IE’s stream of events is called event bubbling, in which events are initially received by the most specific element and then propagated up the ladder to less specific nodes. All modern browsers support event bubbling.

Event capture flow

The Netscape Communicator team came up with an event flow called Event capturing, where events are initially received by less specific nodes and the most specific nodes should receive the event last.

Grade DOM2 events

Dom2-level events specify that the event flow is divided into three phases: event capture phase, in target phase, and event bubbling phase.

2. Event handlers

Functions that respond to events are called event handlers.

HTML event handler

Use event handlers in elements such as:

<input id="btn" type="button" value="Button" onclick="alert(event.type)">
Copy the code
  • For events bound in this way, there is a local variable in the event functioneventIs used to hold event objects.
  • Disadvantages of this approach:
    • 1. The uncertainty of the loading sequence of JavaScript and HTML may trigger the corresponding events and generate errors before the JavaScript is loaded.
    • Scoping in different browsers results in different results.
    • The tight coupling of JavaScript and HTML code requires two changes if the event handler needs to be replaced.

DOM0 level event handler

Methods that appeared in the fourth generation of Web browsers are still supported by all browsers. This is done by assigning the function to an event handler property.

<input id=" BTN "type="button" value=" button" > let BTN = document.getelementById (' BTN ') Btn.onclick = function () {alert(this.id)} // Delete the event btn.onclick = nullCopy the code

For events bound in this way, this can be used in event functions to access any of the element’s attributes and methods, and is handled during the bubbling phase of the event flow.

Dom2-level event handler

Two methods, addEventListener() and removeEventListener(), are provided to specify and remove event handlers, respectively. All DOM nodes contain these two methods.

Three parameters are received:

  • The event name
  • Function of the event handler
  • Boolean, default is false.true: Invokes event handlers during the capture phasefalseThe: bubble phase invokes the event handler
<input id="btn" type="button" value="Button"> let btn = document.getElementById('btn') function fn ( ) { alert('This is A function')} // Btn.addeventlistener ('click', function () {alert('click1')}, false) btn.adDeventListener ('click', fn, False) // Delete event btn.removeEventListener('click', fn)Copy the code
  • Event handlers added using addEventListener can only be removed by removeEventListener, which must be exactly the same as the three parameters passed in.
  • RemoveEventListener cannot remove anonymous functions.

IE event handler

Similar to the DOM2 level, two methods attachEvent() and detachEvent() are provided to specify and delete event handlers, respectively. All DOM nodes contain these two methods.

Event handlers added with attachEvent() are processed in the bubbling phase.

Receives two parameters:

  • The event name
  • Function of the event handler
<input id="btn" type="button" value="Button"> let btn = document.getElementById('btn') function fn ( ) { alert('This is A function')} // Btn.attachevent ('onclick', function () {alert('click1')}) btn.attachevent ('onclick', // Delete event btn.detachevent ('onclick', fn)Copy the code

Differences from other types of methods

  • The main difference is the scope of the event handler. In the case of the attachEvent() method, the event handler takes place in the global scope, where this equals window.
  • 2. The first parameter must beOn + Event nameIn the form.
  • 3. When adding multiple event handlers, execute them in reverse order rather than sequentially.

Implement event handlers across browsers

  • Create an EventUtil object
  • Implement two methods for the EventUtil object: addHandler() and removeHandler()
  • In the following example, you also need to pay attention to the issue of scope
let EventUtil = {
  addHandler: function (el, type, handler) {
    if (el.addEventListener) {
       el.addEventListener(type, handler, false)
    } else if (el.attachEvent) {
       el.attachEvent('on' + type, handler)
    } else {
       el['on' + type] = handler
    }
  },
  removeHandler: function (el, type, handler) {
    if (el.addEventListener) {
         el.removeEventListener(type, handler, false)
      } else if (el.attachEvent) {
         el.detachEvent('on' + type, handler)
      } else {
         el['on' + type] = null
      }
  }
}
Copy the code

3. Event object Event

When a DOM event is triggered, an event object is generated, which contains all the information associated with the event. Includes the element that caused the event, the event type, and other information associated with a particular event.

Event objects in the DOM

Dom-compatible browsers pass event objects into event handlers. Different types of events are triggered, and different methods and attributes can be used.

The event object for all events contains the following properties and methods:

Properties/methods type Read/write instructions
bubbles Boolean read-only Whether the event bubbles
cancelable Boolean read-only Whether you can cancel the default behavior of the event
currentTarget Element read-only The element that the event handler is currently processing
defaultPrevented Boolean read-only When true, the call has already been madepreventDefault()
detail Integer read-only Details related to the event
eventPhase Integer read-only Stages of invoking event handlers: 1. Capture stage; 2. Target stage; 3: bubble stage
preventDefault Function read-only Cancel the default behavior of the event,cancelable === true, you can use this method
stopImmediatePropagation() Function read-only Cancels further capture or bubbling of events while preventing any event handlers from being called
stopPropagation() Function read-only Cancel further capture or bubbling of events,bubbles === true, you can use this method
target Element read-only Object of the event
trusted Element read-only True: Event generated by browser; False: created by the developer using JS
type String read-only Types of events
view AbstractView read-only An abstract attempt to associate with an event. Equivalent to the Window object where the event occurred

instructions

  • Target Is the actual target that triggers the event
  • CurrentTarget Internal to the event handlerthis===currentTarget
  • An event object exists only during the execution of an event handler; Once the event handler completes execution, the event object is destroyed.

Event objects in IE

Depending on how you specify an event handler, the way you get an event object is different.

  • DOM0 levelusewindow.eventGet the Event Object
  • useattachEvent()An event object is passed as a parameter to the event handler, in which case the event object can also be retrieved from the Window object.

The event object for all events contains the following properties and methods:

Properties/methods type Read/write instructions
cancelBubbles Boolean Read/write Default false, true: can cancel event bubbling, with DOMstopPropagation()In the same way
returnValue Boolean Read/write Default true, false: Cancels the default behavior of events, as in the DOMpreventDefault()In the same way
srcElement Element read-only The target of the event, and the DOMtargetAttribute is the same
type String read-only Types of events

instructions

  • Because the scope of an event handler is determined by how it is specified, it is best to usesrcElementTo determine the event target.

Cross-browser event objects

For the differences between IE and DOM events, you can continue to supplement the EventUtil object created earlier to resolve compatibility issues.

let EventUtil = { addHandler: function (el, type, handler) { if (el.addEventListener) { el.addEventListener(type, handler, false) } else if (el.attachEvent) { el.attachEvent('on' + type, handler) } else { el['on' + type] = handler } }, removeHandler: function (el, type, handler) { if (el.addEventListener) { el.removeEventListener(type, handler, false) } else if (el.attachEvent) { el.detachEvent('on' + type, handler) } else { el['on' + type] = null } }, -------- getEvent: function (event) {return event? Event: window.event}, getTarget: function (event) { return event.target || event.srcElement }, preventDefault: Function (event) {// Prevent event preventDefault if (event.preventDefault) {event.preventDefault()} else {event.returnValue = true} }, stopPropagation: Function (event) {// Stop bubbles if (event.stopPropagation) {event.stopPropagation()} else {event.cancelbubbles = true}} }Copy the code

Thank you for your support

1. If you like the article, you can “share it, like it, and read it”.

2, author nickname: SaucXS, songEagle, Songbao write code. “Songbao write code” public number author, daily question, laboratory, etc. A bytedance engineer who loves to toss, is committed to the whole stack, and is working hard to grow, star Sea, the future can be expected. Inside push bytedance each department each post.

3, long press the picture below, pay attention to “Songbao write code”, is to obtain the development knowledge system construction, selected articles, project actual combat, laboratory, a daily interview question, advanced learning, thinking about career development, involving JavaScript, Node, Vue, React, browser, HTTP, algorithm, side related, small program and other fields. Hope can help you, we grow up together ~

Byte push benefits

  • Reply “school admission” to get internal push code
  • Reply “Social recruitment” to get internal promotion
  • Reply “intern” to get internal push

There will be more benefits later

Learning Material Benefits

Reply “Algorithm” to obtain algorithm learning materials

Previous “Question of the Day”

1. JavaScript && ES6

  • Interviewer: What is the difference between prototype chain and constructor combination method inheritance and primitive type inheritance?

  • Interviewer: What is the main difference between var and const,let?

  • Interviewer: What about the binding of this in JS?

  • Q: What about the understanding of webSockets in JS?

  • Q: What do you understand about XMLHttpRequest objects in JAVASCRIPT?

  • Question 18: Ajax in JS extends Comet across domains?

  • Q: What is the understanding of event flow, event handler and event object in JS?

  • 第 16 题 : How to perform client detection comprehensively in JS?

  • Interviewer: What are the methods for judging the JS type?

  • Interviewer: Tell me about your creation and extension of JS objects

  • [‘1’, ‘2’, ‘3’]. Map (parseInt) output, the reason, and the extension?

  • Q: What is the execution process of the JS engine?

  • Q: What is the execution process of JS engine?

  • Q: Tell me more about the JS data type

  • Q: What is your understanding of ES6 proxy?

  • Interviewer: What is the difference between “for in” and “for of”?

  • 6. How can Async/Await Async/Await Async?

  • 3. “Question of the Day” The interviewer asks you what you think of Promise?

  • In ES6, why do we use Symbol?

2. Browser

  • 9. Doesn’t requestAnimationFrame smell good?

3, Vue

  • How does VUE data binding work?

4, HTML 5

  • 第 29题 : What is the new attribute of htML-HTML5?

5, the algorithm

  • Interviewer: What do you know about graph theory?

  • 第 27题 (27题) Algorithm: How to use multiple solutions to achieve a jump game?

  • 第 26题 : What is the longest common prefix?

  • 第 25题 : Heap data structure – the first K high frequency elements?

  • 第 24题 【 daily 1 题】(24题) Algorithm: Greedy algorithm – how to fuel around the world?

  • Question 4: How to find repetitive elements in a scientific and efficient way?

6, the Node

  • 第 23题 : Describe the Event Loop in detail?

7, the Http

  • 1. “How does an interview question trigger deep soul searching?”