introduction

This JavaScript guy is doing some tricks again! This time, we will focus on the JavaScript event-driven model and event processing mechanism. Don’t underestimate this guy, it is a key element in the heart of JavaScript, responsible for the responsiveness and interactivity of JavaScript. In other words, it determines whether your web page moves like a rabbit and reacts like lightning.

First, we have to understand the basic concept of the JavaScript event-driven model, which is the basis for understanding how JavaScript responds to user operations. Next, we’ll uncover how this model works and understand how it goes from receiving an event to executing an event handler.

Of course, we’ll also explore event listeners and event handlers, two of the keys to making your web pages responsive. Event bubbling and event capturing, these two seemingly complex concepts, are actually rules that describe how events propagate in the DOM tree.

Event delegation and its advantages, this seemingly advanced topic, is actually a clever technique of using event bubbling, allowing us to process events more efficiently. And JavaScript’s default event behavior, this is a way to make your web pages more user-friendly.

Custom Events and Triggers, a powerful tool that allows you to create and trigger your own events. Finally, we will see asynchronous event processing and Promise, Async/Await model, which is JavaScript’s artifact for handling complex asynchronous events.

Okay, that’s a lot, let’s dive into the world of JavaScript’s event-driven model and event processing mechanism! Let’s take a look at how many secrets JavaScript has hidden

1. Basic concepts of JavaScript event-driven model

The event-driven model of JavaScript is a programming model. Its basic idea is that the running of the program is not controlled by the sequence of code, but is triggered by events. Events can be user behaviors, such as clicks, sliding, keyboard input, etc., or browser behaviors, such as page loading, window size changes, etc. When these events occur, JavaScript generates an event object and passes it to the corresponding event handler function, which determines how to respond to the event.

In JavaScript, the event-driven model is mainly reflected in two aspects: first, event listening, that is, binding the event processing function to a specific event through addEventListener or on+event name; second, event processing, that is, when an event occurs When, the corresponding event processing function is executed.

The advantage of the event-driven model is that it allows the program to perform other processing while waiting for events to occur, improving the efficiency and response speed of the program. At the same time, it also makes the structure of the code clearer and easier to understand and maintain. Therefore, the event-driven model is widely used in JavaScript and is one of the key knowledge points for understanding and mastering JavaScript.

2. How the JavaScript event-driven model works

In the JavaScript event-driven model, there are mainly the following steps:

  1. Event monitoring: First, we need to monitor events for a certain element, such as click events, scroll events, etc. This step is usually implemented through the addEventListener method.

  2. Event triggering: When the user performs certain operations (such as clicking, scrolling, etc.), if the events corresponding to these operations are monitored, then this event will be triggered.

  3. Event processing: When an event is triggered, an event object will be generated, and this event object will be passed to the event processing function. The event processing function will perform corresponding processing according to the event object.

  4. Event loop: JavaScript uses a single-threaded model, but multiple events can be processed through the event loop. When an event is triggered and processed, JavaScript will check to see if there are other events that need to be processed. If so, it will continue to process the next event. This is the so-called event loop.

  5. Asynchronous processing: Due to the single-threaded model of JavaScript, for some tasks that require long-term processing, if they are processed directly on the main thread, it will block the execution of subsequent code. To solve this problem, JavaScript provides an asynchronous processing mechanism. In asynchronous processing, long-term tasks will be processed on a separate thread. The main thread will continuously check the status of this thread when processing other events. When it is completed, the main thread will receive an event. Then execute the corresponding callback function.

Through the above steps, the JavaScript event-driven model can effectively handle user interaction requests, making the Web page have good interactivity. At the same time, through the asynchronous processing mechanism, JavaScript can also handle some complex and time-consuming tasks, improving program execution efficiency.

3. Event monitoring and event processing functions

In JavaScript, event listening and event processing functions are the core part of the event processing mechanism. When a user interacts with a web page, such as clicking a button or pressing a key on the keyboard, an event is generated. In order to respond to these events, we need to set up an event listener (Event Listener) in JavaScript.

An event listener is a JavaScript function attached to a specific HTML element. When a specific event occurs, this function will be triggered. For example, we can set a click event listener on a button element, and when the user clicks the button, a JavaScript function will be executed.

The triggered JavaScript function is what we call the event handler (Event Handler). The task of the event handling function is usually to perform certain tasks based on the generated events. For example, when a user clicks a submit button, the event handler might collect the data the user entered in the form and send that data to the server.

In JavaScript, we can use the addEventListener method to set up event listeners. For example:

  var btn = document.getElementById('my-btn');
  btn.addEventListener('click', function() {
      alert('Button is clicked!');
  });

The above code first obtains the button element with the id of ‘my-btn’, and then sets a click event listener for this button. When the user clicks this button, the event processing function will be triggered, and a prompt box will pop up to display ‘Button is clicked!’.

  In addition, the event handling function can also receive an event object (Event Object) as a parameter, which contains various information related to the generated event. For example:

  btn.addEventListener('click', function(event) {
      console.log('Button is clicked!');
      console.log('Event type: ' + event.type);
      console.log('Clicked element: ' + event.target);
  });

 When an event handler is triggered, it receives an event object. This event object has many properties that can provide detailed information about the event, such as the event type (event.type), the element that triggered the event (event.target), etc.

4. Event bubbling and event capturing

Event bubbling and event capturing are the two main methods of event propagation in JavaScript. Understanding how these two mechanisms work is of great significance for us to write efficient and maintainable JavaScript code.

Event bubbling, as the name suggests, is like bubbles emerging from the bottom of the water. Events will start from the innermost element and then propagate upward to the outermost node layer by layer. For example, if you click a nested button, the event will start from the button and bubble up to the parent element layer by layer until you reach the document object.

Code example:

  document.querySelector('div').addEventListener('click',function(){
    console.log('div clicked');
  },false);
  
  document.querySelector('button').addEventListener('click',function(){
    console.log('button clicked');
  },false);

When the button is clicked, the console will first print “button clicked” and then “div clicked”.

Event capture is another way of event propagation. It is the opposite of event bubbling. Events start from the outermost layer and then propagate inward layer by layer.

Code example:

  document.querySelector('div').addEventListener('click',function(){
    console.log('div clicked');
  },true);
  document.querySelector('button').addEventListener('click',function(){
    console.log('button clicked');
  },true);

When the button is clicked, the console will first print “div clicked” and then “button clicked”.

In actual development, we can choose to use event bubbling or event capturing as needed. Understanding these two mechanisms can help us better manage and control events and avoid confusion and conflicts in event processing.

5. Event delegation and its advantages

Event delegation, also known as event proxy, is a technique for handling events in JavaScript. In event delegation, instead of directly binding an event to an element, the event is bound to its parent element or ancestor element. Through event bubbling, the identity of the event target is used to judge, and then the corresponding event processing is performed. function.

For example, there is a list element, and we need to bind a click event to each list item. The traditional approach is to traverse each list item and perform event binding on each list item. And if we use event delegation, we only need to bind the event once on its parent element (that is, on the ul or ol element).

The advantages of doing this are mainly the following two:

1. Improve performance: avoid a large number of event bindings, reduce memory usage, and improve performance.

2. Processing of dynamic elements: For dynamically added elements, there is no need to re-bind events. You only need to bind events on their parent elements or ancestor elements. This is useful when dealing with dynamic content, such as AJAX loaded content.

The implementation code is as follows:

document.getElementById('parent').addEventListener('click', function(e){
  if(e.target.tagName.toLowerCase() === 'li'){
    // 
  }
});

In the above code, we bound the event on the parent element and checked the target element of the event in the event handler function. Only when the target element is a li element, the corresponding event handler function will be executed. This is the basic idea of ​​event delegation.

6. JavaScript’s default event behavior

JavaScript’s default event behavior refers to the browser’s default response to certain events. For example, clicking on a link will navigate to a new URL, submitting a form will send a request to the server, right-clicking will pop up the context menu, etc. These are the browser’s default behaviors for specific events.

In JavaScript, we can prevent these default behaviors using the event object’s preventDefault() method. This method tells the browser not to perform the default action associated with the event. It should be noted that not all events have default behaviors, only those events with default behaviors can use this method.

For example, we can prevent the default redirect behavior of links:

document.querySelector('a').addEventListener('click', function(event) {
      event.preventDefault();
      console.log('click');
  });

In this example, when the user clicks on the link, the browser’s default behavior (jumping to the link’s URL) is suppressed and a message is output instead.

However, using the preventDefault() method does not prevent the event itself from occurring. The event will still be dispatched to the target element and bubbled or captured when needed. preventDefault() just prevents the browser from responding to the event by default.

In addition, there are some events, such as scroll events, whose default behavior cannot be canceled. For these events, calling the preventDefault() method has no effect.

Understanding and properly utilizing JavaScript’s default event behavior can help us better control the behavior of the page and improve the user experience.

7. Custom events and triggers

In the JavaScript event mechanism, in addition to common events triggered by user interaction or browser behavior, such as click, load, etc., we can also create custom events and trigger them through code. Custom events allow us to send customized information when needed, allowing our applications to respond differently according to different situations.

To create a custom event, you first need to use the Event constructor, which receives one parameter, which is the name of the event. For example, we can create a custom event called “myEvent”:

  let myEvent = new Event('myEvent');

With the event object, we can trigger this event on any DOM object. The event is triggered using the dispatchEvent method, which receives an event object as a parameter. For example, we can trigger the myEvent event we just created on the document object:

document.dispatchEvent(myEvent);

Of course, the real power of custom events is that we can add event handlers to them so that specific code can be executed when the event occurs. Like other events, we can use the addEventListener method to add event handlers to custom events:

document.addEventListener('myEvent', function(e) {
    console.log('myEvent happen!');
  });

In the above code, when the myEvent event occurs on the document object, “myEvent occurred!” will be output.

Custom events and triggers provide us with greater flexibility. We can send events according to our own needs and execute specific code when events occur.

8. Asynchronous event processing and Promise, Async/Await models.

JavaScript is a single-threaded language, which means it cannot handle multiple events at the same time. However, events in real life often occur concurrently, which requires the use of asynchronous event processing. Asynchronous event handling allows JavaScript to continue performing other operations while waiting for an operation to complete without being blocked.

Promise is an asynchronous programming solution that represents an event that may eventually complete (resolve) or fail (reject). A Promise object represents an operation that has not yet completed but will be completed in the future.

Promise has three states: pending, resolved and rejected. The pending status indicates that the Promise instance has been created but has not yet been completed. The resolved state indicates that the Promise has been completed and the operation was successful. The rejected status indicates that the Promise has been completed, but the operation failed.

Async/Await is built on Promise and is a more elegant asynchronous processing method. Async is the keyword that declares a function to be asynchronous, and Await is the keyword that waits for an asynchronous operation to complete.

Using Async/Await, we can write asynchronous code in a synchronous manner, making the code more concise and readable. Here is an example using Async/Await:

async function asyncFunc() {
        try {
            let response = await fetch('http://api.example.com/data');
            let data = await response.json();
            console.log(data);
        } catch (err) {
            console.error(`Error: ${err}`);
        }
    }

The above code first uses the fetch function to obtain remote data, then waits for the obtained Promise object to resolve, then converts the result to JSON format, and finally outputs the data. If an error occurs during the process, it will be caught and processed by the catch block.

Asynchronous event processing and the Promise and Async/Await models provide JavaScript with powerful asynchronous programming capabilities, allowing us to better handle concurrent events and improve application response speed and user experience.

Summarize

      Hi, our journey of JavaScript event-driven model and event handling mechanism comes to an end! The event-driven model of JavaScript is like a careful postman, always alert and ready to capture and process events from the user or system. The event processing mechanism is like a skilled chef, processing each event carefully to make our web pages lively. Event listening and handling functions are our magic tools that allow us to respond appropriately to events. Event bubbling and capturing are like a wonderful game of table tennis, allowing us to gain a deeper understanding of events. Event delegation is our little secret that allows us to handle large numbers of events with ease. The default event behavior is the true nature of each event. We can choose to accept it or prevent it. Custom events and triggers give our applications greater flexibility. Finally, asynchronous event processing and Promise and Async/Await models make our code more elegant and more in line with human thinking. All this makes us fall in love with JavaScript even more, let us look forward to the next learning journey together!

Leave a Reply

Your email address will not be published. Required fields are marked *