JS event of interview reinterview

JS event model

JavaScript events make web pages interactive and interactive, and we should know more about them for development purposes. In a variety of browsers, JavaScript event models are mainly divided into three types: original event model, DOM2 event model, IE event model.

Original event model (DOM0 event model)

This is a model supported by all browsers. It is the original event model. For the original event model, there is no event flow, events are handled as soon as they are triggered

  1. Specify attribute values in HTML code<button id="demo" type="button" onclick="doSomeTing()" />
  2. In the JS codedocument.getElementsById('demo').onclick = doSomeTing()

IE a model

The IE event model has only two steps: the element’s listener function is executed, and the event bubbles along the parent node to the window.

  • implementation
<button id="btn">+<button>

btn.attachEvent('onclick'.() = >{
  console.log(IE);
})
Copy the code

The attachEvent function takes two arguments, the first the event type and the second the event handler

DOM2 event model

This model is a special W3C standard model that most modern browsers follow. An event sending consists of three phases

  • Event capture phase, event target phase, event bubbling phase

The following figure

  • Event capture: When an element fires an event, the window emits a stream of events from the window to the target element node until the target element node is reached. This process is called the target capture phase, which by default does not fire listeners
  • Target phase: When the target element is reached, the handler corresponding to the target element change event is executed.
  • Event bubbling: The flow of events from the target element node to the window stream is called event bubbling
  • implementation
<button id="btn">+<button>

var btn = document.getElementById('btn')
btn.addEventListener('onclick'.() = >{
  console.log(DOM2);
},false)
Copy the code

The addEventListener function takes three arguments, the first is the event type, the second is the event handler, and the third is to determine whether capture is enabled. The default is false.

Differences between the three event models

DOMo:

  1. This refers to the bound element
  2. Most compatible (compatible with all browsers)
  3. When multiple events of the same type are bound, the next one overwrites the previous one
  4. Bubbling phase

IE model:

  1. This points to the window
  2. Poor compatibility (only runs in Internet Explorer)
  3. When multiple events of the same type are bound, they are executed one after the other
  4. There are only two parameters
  5. Target phase, bubble phase
  6. Window.event. srcElement gets the target element

DOM2:

  1. This refers to the bound element
  2. Medium compatibility (works with most current browsers)
  3. The former is executed when multiple events of the same type are bound
  4. Three parameters
  5. Capture phase, target phase, bubble phase
  6. Event. target Gets the target element

The event,

An event is encapsulated as an event object, which contains all the relevant information about the event when it occurs and the operations that can be performed on the event

  • Common properties and methods of an event object

If you look at the properties of MouseEvent objects, you’ll notice that there are a lot of X/Y properties that depend on the location of the event, as explained in detail below

  1. X/ y, the same value as clientX/clientY, represents the distance to the left/top of the viewable area of the browser (excluding the toolbar area);
  2. PageX /pageY, the distance to the left/top of the page, differs from clientX/clientY in that it does not change with the position of the scroll bar;
  3. ScreenX /screenY, the distance to the left/top of the computer monitor, drag your browser window to see the change;
  4. AyerX /layerY, like offsetX/offsetY, represents the distance to the left/above the parent element that has the positioning attribute.

Other common properties of the event object

  • Common attributes of event objects in the DOM event model:
  1. Type Indicates the event type
  2. Target Gets the event target
  3. StopPropagation () prevents event bubbling
  4. PreventDefault () prevents event default behavior
  • Common attributes of event objects in IE event model:
  1. Type Indicates the event type
  2. SrcElement gets the event target
  3. CancelBubble prevents events from bubbling
  4. ReturnValue blocks the event default behavior

Prevents bubbling, capturing, and default events

  • To prevent a bubble

DOM using event. StopPropagation (), IE is to use window. The event. The cancelBubble = true

function stopBubble(e){
    if(e.stopPropagation){  //DOM
        e.stopPropagation()
    }else{      //IE
        window.event.stopBubble = true}}Copy the code
  • Stop the capture

IE does not have capture phase, so there is no need to block. DOM blocks capture code as event.stopPropagation().

  • Blocking default events

The DOM uses event.preventDefault(),IE uses window.event.returnValue = false

function stopDefault(e){
  if(e.preventDefault){  //DOM
    e.preventDefault()
  }else{     // IE
    window.event.returnValue = false}}Copy the code

Pay attention to

  1. Event.stoppropagation () prevents capturing and bubbling events

  2. Event. StopImmediatePropagatipn () also can prevent the event target element node structure (dom) registered other similar events

JS event delegate

Delegate an event that was originally mounted on you to its parent element. Through the event bubbling and event capture mechanism, when the event of the child element is triggered, the event stream bubbling through the parent element is monitored by the listener function. At this time, the event. Target can be used to obtain the specific element that triggered the event. This is where the parent element replaces the child element.

<ul id="ul1">
<li>1</li>
<li>2</li>
<li>3</li>
</ul>

 // DOM2
var ul2 = document.getElementById('ul1')
ul2.addEventListener('click'.(e) = >{
  console.log(e.target.innerText);
})

// Optimize (compatible with IE and DOM0)
let ul1 = document.getElementById('ul1')
console.log(ul1);
ul1.onclick = function(e){
  let event = e || window.event
  let curTarget = event.target || event.srcElment
  if(curTarget.tagName.toLowerCase() === 'li') {console.log(curTarget.innerText); }}Copy the code
  • Note that not all events can be event proxies, but only those that freely support capture and bubble mechanisms
  • Events such as Blur, Focus, Load and Unload cannot bubble

advantages

  1. It can greatly save memory usage and reduce event registration
  2. No event binding is required for new content child objects, which is suitable for dynamic content

disadvantages

  1. Event misjudgment can occur, tying events to DOM structures that do not require event delegation

Custom events

I’m just going to generalize about it, not go into details. Those interested can check out his article at juejin.cn/post/684490…

What are custom events

An event itself is a means of communication, a message. In the front-end development world, JS and HTML often interact with each other through events. When some base event does not satisfy our business, we can try custom events to solve the problem

implementation

Currently, the two main ways to implement custom events are created by the JS native Event() constructor and CustomEvent() constructor.

demo

Event()

// Create a pingan event that supports bubbling and cannot be cancelled
let myEvent = new Event("pingan", {"bubbles":true."cancelable":false});

document.dispatchEvent(myEvent);

// Events can be fired at any element, not just document
testDOM.dispatchEvent(myEvent);
Copy the code

CustomEvent()

// Create a pingan event that passes an object
let myEvent = new CustomEvent("pingan", {
  detail: { name: "wangpingan"}});// Add the appropriate event listener
window.addEventListener("pingan".e= > {
  alert(The pingan event is triggered. Yes${e.detail.name}The trigger. `);
});
document.getElementById("leo2").addEventListener(
  "click".function () {
    // Send events
    window.dispatchEvent(myEvent); })Copy the code

The difference between Event() and CustomEvent()

  1. Event()Suitable for creating simple custom events, whileCustomEvent()Supports custom events for parameter passing, which supportsdetailParameter, as the data to be passed in the event, and inEventListenerTo obtain.

The JS script is loaded and the page is loaded

In the process of work, there is often a need to load on demand, that is, after the script is loaded or the page number is loaded, a callback function is returned and relevant operations are carried out in the callback function. Then how to determine whether the page or JS script is loaded or not?

  • Here are some ways to find out

How do I determine if the page is loaded

  • Window.onload = function(){} Execute the function after the page is loaded
  • $(documnet).ready(functiion(){})
  • document.onreadystatechange = function(){}

How to determine if the JS script is loaded successfully

  • js.onload
  • js.onreadystatechnage