Technology Sharing: Explanation of Events (Event Trigger) in NodeJS

  In Node.js, Event is a very core module, and most of the core modules are basically used or inherited from this module.

  The Event module is very similar to the EventTarget interface that we learned in Javascript before. For this module, what we can do is not only simple use, but also can be extended on the basis of this module, you think about onclick, onmousemove in JS

  Don't be wordy, just go to the code!

  Because the event module is a relatively abstract thing, it is not suitable to describe it in a large language, so I decided to directly upload the code, first realize the function and see the effect. Let's experience the functions of this module together.

  Extend the custom class

  At the front end, we can monitor an element event, for example


  This approach is actually to add event listeners to the DOM objects in the page. It is impossible to directly add event listeners to an object in Node.js, because our custom classes or objects do not implement or inherit the Events module. .

  If you want to use the Events module, you need to import the module first.


  Next is the implementation of the specific code:


  The above code is to extend our custom class.

  In the above code, we used two methods in the event module: on(), emit(). These two methods are for registering events and triggering events.

  There are far more useful methods in the event module than these two. Here are a few more commonly used methods.

  on(): Register the event and add the name of the event to be monitored to the end of the listener array.

  addListener(): Same as above.

  off(): Remove the event, remove the name of the event being monitored from the listener array.

  removeListener(): Same as above.

  eventNames(): Returns an array of event names of registered listeners. The value in the array is a string or a Symbol.


  Because the concept of events is relatively abstract, most of our developers don't really like to use the Events module to implement monitoring. More often we may prefer to monitor a function or method in the form of a callback function.

  Therefore, our learning of the Events module is not only to add events to custom classes in the future, but also to have a certain understanding of the overall architecture of Node.js knowledge points and understand the ins and outs of the knowledge points.

  After learning Events, we can also understand why many core modules we learn later have on() and off() methods, because they all inherit the Events module.

  I hope this article can be helpful to you who want to learn java knowledge with zero foundation.

  This article is from Qianfeng Education , please indicate the source for reprinting.

Guess you like