varEventemitter=require (' Events '). EventemittervarLife=NewEventemitter ();//Comfort for Comfort, the name of the letter;//fondness for indulgence, the letter of the name;//officials recommend that the maximum number of events to monitor not more than 10, too many words may lead to memory leaks, of course, this value can be modified by the Setmaxlisteners () method to modify;Life.setmaxlisteners (3) Life.on (' Comfort ',function(WHO) {//listening, seeking comfort,Console.log (' Give ' +who+ ' pour water! ‘);}) Life.on (' Comfort ',function(WHO) {//listening, seeking comfort,Console.log (' rub shoulders ' to ' +who+ ');}) Life.on (' Comfort ', Zuofan); functionZuofan (WHO) {Console.log (' Cook ' for ' +who+ ');} Life.on (' Fondness ', Maiyifu); Life.on (' Fondness ', Jiaogongzi); functionMaiyifu (WHO) {Console.log (' Buy clothes ' for ' +who+ ');}functionJiaogongzi (WHO) {Console.log (' Pay ' +who+ ');}//Life.removelistener (' comfort ', zuofan);//removal of events;Life.emit (' comfort ', ' hubby ')//Invoke EventLife.emit (' fondness ', ' wife ')//Invoke Event//Console.log (life.emit (' comfort ', ' hubby '))//whether to invoke the event, return true,false;Console.log (' Things for my husband: ' +life.listeners (' comfort '). Length)//number of events;Console.log (' Things for my wife: ' +life.listeners (' fondness '). Length)//number of events;
Open cmd and Run node Events.js as shown in:
First listen to the event, then use the emit () method to invoke, remove the event is the RemoveListener () method;
It is important to note that the listener event can pass through the anonymous function or the real name function, but when removing the event, you must pass in the real name function, and the incoming anonymous function will have an error;
Nodejs Event Listener Removal Event