2012-04-15 208 views
4

希望得到一些幫助。我是Nodejs的新手,想知道是否可以刪除這個自定義事件發射器。大部分代碼來自Pedro Teixeira的Hand on nodejs。我的底部功能是試圖刪除您在本書中設置的自定義事件發射器。的NodeJS刪除事件偵聽器

var util = require('util'); 
var EventEmitter = require('events').EventEmitter; 

// Pseudo-class named ticker that will self emit every 1 second. 
var Ticker = function() 
{ 
    var self = this; 
    setInterval(function() 
    { 
     self.emit('tick'); 
    }, 1000); 
}; 

// Bind the new EventEmitter to the sudo class. 
util.inherits(Ticker, EventEmitter); 

// call and instance of the ticker class to get the first 
// event started. Then let the event emitter run the infinante loop. 
var ticker = new Ticker(); 
ticker.on('tick', function() 
{ 
    console.log('Tick'); 
}); 

(function tock() 
{ 
    setInterval(function() 
    { 
     console.log('Tock'); 
     EventEmitter.removeListener('Ticker',function() 
      { 
       console.log("Clocks Dead!"); 
      }); 
    }, 5000); 
})(); 

回答

5

您需要使用ticker對象的removeListener方法,而不是EventEmitter。第一個參數是事件名稱,第二個 - 鏈接到要刪除的事件偵聽器。

此代碼應工作:

var util = require('util'); 
var EventEmitter = require('events').EventEmitter; 

// Pseudo-class named ticker that will self emit every 1 second. 
var Ticker = function() 
{ 
    var self = this; 
    setInterval(function() 
    { 
     self.emit('tick'); 
    }, 1000); 
}; 

// Bind the new EventEmitter to the sudo class. 
util.inherits(Ticker, EventEmitter); 

// call and instance of the ticker class to get the first 
// event started. Then let the event emitter run the infinante loop. 
var ticker = new Ticker(); 
var tickListener = function() { 
    console.log('Tick'); 
}; 
ticker.on('tick', tickListener); 

(function tock() 
{ 
    setTimeout(function() 
    { 
     console.log('Tock'); 
     ticker.removeListener('tick', tickListener); 
     console.log("Clocks Dead!"); 
    }, 5000); 
})(); 
2

https://nodejs.org/api/events.html#events_emitter_removelistener_eventname_listener 如果選中使用上面的鏈接是EventEmitter.removeListener("eventName",listenerFunc) 所以讓我們假設我有以下情形

const {EventEmitter} =require("events") 
//lets construct our emitter object 
const myEmitter=new EventEmitter() 
//and our listener which has to be a named func if we want to identify it later for removing 
function myListenerFunc(d){ 
    console.log(d) 
    } 
//adding the emitter 
myEmitter.on("data",myListenerFunc) 
//lets remove it after a while 
//... some time passed something was done 
//... some more time passes something else was done 
//we dont need the listener anymore lets remove it 
myEmitter.removeListener("data",myListenerFunc) 
//alternatively if you want to remove all listeners 
myEmitter.removeAllListeners(["data"/* if you need list all the event names in this array*/])