Home >Web Front-end >JS Tutorial >Overview of js custom events and event interaction principles (1)_javascript skills
In JS, events are the main way for JS to interact with the browser. Events are a design pattern called the Observer, which is a technique for creating loosely coupled code. Objects can publish events to indicate the arrival of an interesting moment in the object's life cycle. Other objects can then observe the object, wait for these interesting moments to come and respond by running code.
The observer pattern consists of two types of objects: subjects and observers. The subject is responsible for publishing events, while observers observe the subject by subscribing to these events. A key concept of this pattern is that the agent does not know anything about the observer, meaning that it can exist on its own and function normally even if the observer is not present. Observers, on the other hand, know about the subject and can register callback functions (event handlers) for events. When it comes to the DOM, the DOM element is the subject and your event handling code is the observer.
Events are the most common way to interact with the DOM, but they can also be used in non-DOM code - by implementing custom events. The concept behind custom events is to create an object that manages events and let other objects listen to those events. To put it simply, we hope that when the program is running, there may be many routes. If the program runs to a special place, we hope to run the code in the user registration method immediately, and then continue running after the run is completed. This process is called monitoring. .
For example, create a file MyEvent.js file and create a class in it: