Understanding and Analysis of node. js event monitoring and triggering
This article mainly introduces the understanding and analysis of node. js event monitoring and triggering, and compares node. js and jQuery's practical skills on event monitoring in the form of examples, which helps to deepen the understanding of node. js, for more information, see
This article analyzes the monitoring and triggering of node. js events. Share it with you for your reference. The specific analysis is as follows:
Regarding the event-driven node. JS, I still did not understand it after reading "deep dive into node. js" (it may be a bit deep, or I cannot understand it well ), today, I saw an article about monitoring and triggering node. js events in the Turing community. The example is easy to understand, so I also understand the node. js event driver.
The following references the Turing community article (Address: http://www.ituring.com.cn/article/177478)
First, let's take a look at the Event module of nodejs:
Most modules in Node. js are inherited from the Event module. The Event module (events. EventEmitter) is an implementation class in simple Event listener mode. Its objects include addListener, on, once, removeListener, removeAllListeners, emit, and other basic event listening modes.
First, let's look at an example:
?
1 2 3 4 5 6 7 8 9 |
Var events = require ("events "); Var emitter = new events. EventEmitter (); // creates an object for the event listener // Listen to the event some_event Emitter. on ("some_event", function (){ Console. log ("event triggered, call this callback function "); }); SetTimeout (function (){ Emitter. emit ("some_event"); // triggers the event some_event },3000 ); |
Seeing this example reminds me of jQuery's custom events:
?
1 2 3 4 5 6 |
// Bind a hello event to the element Element. on ("hello", function (){ Alert ("hello world! "); }); // Trigger the hello event Element. trigger ("hello "); |
In this case, it is easy to understand the monitoring and triggering of node. js events. Emit is equivalent to trigger events in jQuery.
I hope this article will help you design nodejs programs.