The event emitter is another important asynchronous programming technique in node that is outside of the callback function. In the graphics interface programming library such as MFC, event emitter is very common, for example, mouse click event, click the mouse, will trigger the mouse click Function-Event emitter trigger event, and after the event is triggered to process them. In the node API component, such as HTTP server, TCP server and so on have been made the event emitter, so mastering the Event launcher programming method is very important.
Using on to add listeners
Steps:
- Declaring event emitter classes
- Creating an Event Emitter object
- Using on to add an event emitter
- Using emit to launch events
//事件发射器类声明var EventEmitter = require("events").EventEmitter;//创建事件发射器varnew EventEmitter();//使用on添加监听器emitter.on("hello",function(){ console.log("Hello");});//使用emit函数发射事件emitter.emit("hello");
Adding events using AddListener
Example:
//事件发射器类声明var EventEmitter = require("events").EventEmitter;//创建事件发射器varnew EventEmitter();//使用addListener添加监听器emitter.addListener("hello",function(){ console.log("Hello");});//使用emit函数发射事件emitter.emit("hello");
Registering an event listener with parameters
The registered listener can take the parameters directly and add the corresponding parameters when the emit launch event. Example:
//事件发射器类声明var EventEmitter = require("events").EventEmitter;//创建事件发射器varnew EventEmitter();//使用on添加监听器emitter.on("hello",function(name,age){ console.log(name+" is "+age);});//使用emit函数发射事件emitter.emit("hello","king","21");
Remove event Emitter
Use Removealllisteners to remove all listeners from the Hello event, and use RemoveListener to remove the Hello event-specific listener, example:
//Event emitter class declarationvar eventemitter = require ("Events"). Eventemitter;//Create event emitterVarEmitter= new Eventemitter ();//use on to add listenersEmitter. On ("Hello", function (name,age) {Console.Log(name+"is"+age);});//using the emit function to emit eventsEmitter.Emit("Hello","King","very");//Add event to remove listenerEmitter. On ("Quit", function (name) {Emitter. removealllisteners (name);//Remove event listener named name});//Remove Hello this eventEmitter.Emit("Quit","Hello");//Call again to see the effect (there is no effect because there is no listener for this event now)Emitter.Emit("Hello","King","very");
"Node. JS Basics" (vii) node asynchronous programming event emitter