Home  >  Article  >  Web Front-end  >  Overview of js custom events and event interaction principles (1)_javascript skills

Overview of js custom events and event interaction principles (1)_javascript skills

WBOY
WBOYOriginal
2016-05-16 17:42:321074browse

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:

Copy the code The code is as follows:

function MyEvent(){
this.handler;
}
MyEvent.prototype={
addHandler:function(handler)
{
this .handler=handler;
},
fire:function()
{
this.handler();
},
removeHandler:function()
{
this.handler=null;
}
}

The above is a class created using the idea of ​​​​js prototype. If the reader does not know much about it, you can check the relevant information. The MyEvent type has a separate attribute handler, which is used to store the event handler (that is, the method registered by the user). There are also three methods: addHandler(), used to register an event handler; fire(), used to trigger an event; and removeHandler(), used to unregister the event handler.

Then we can use it like this, create a new html file and put it in the same directory as MyEvent.js for easy reference. The code is as follows:
Copy code The code is as follows:


< head>