2012-04-15 12 views
4

いくつかの助けを求めるために探しています。私はNodejsが初めてで、このカスタムイベントエミッタを削除することが可能かどうか疑問に思っています。このコードのほとんどは、Pedro Teixeiraの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

EventEmitterではなく、tickerオブジェクトのremoveListenerメソッドを使用する必要があります。最初の引数は、削除するイベントリスナーへの2番目のリンクであるイベント名です。

このコードべき作品:

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*/]) 
次していると仮定することができます
関連する問題