This article analyzes the listening and triggering of nodejs events. Share it for your reference. The specific analysis is as follows:
Regarding the event-driven event driver of nodejs, I still haven't understood it after reading "Nodejs In-depth" (maybe I wrote it a bit deeper, or I don't have good understanding enough). Today, I saw an article about the listening and triggering of nodejs events in the Turing community. Since there are many examples given, it is easy to understand, so I roughly understand the nodejs event driver.
The following content refers to the articles of the Turing community (address: http://www.ituring.com.cn/article/177478)
First, let’s learn about the Event module of nodejs:
Most modules in Node.js are inherited from the Event module. The Event module (events.EventEmitter) is a simple implementation class for event listener mode. Its object has basic event listening mode implementation such as addListener, on, once, removeListener, removeAllListeners, emit, etc.
Let’s first look at an example:
var events = require("events");var emitter = new events.EventEmitter();//A object of the event listener is created// Listen to event some_eventemitter.on("some_event", function(){ console.log("event trigger, call this callback function");});setTimeout(function(){ emitter.emit("some_event"); //Trigger event some_event},3000);Seeing this example reminds me of the custom events of jQuery:
//Bind the hello event element.on("hello",function(){ alert("hello world!");});//Trigger("hello");With this comparison, it is easy to understand the listening and triggering of nodejs events. emit is equivalent to trigger event in jQuery.
I hope this article will be helpful to everyone's nodejs programming.