Nodejs删除事件侦听器

时间:2012-04-15 18:59:10

标签: node.js

希望得到一些帮助。我是Nodejs的新手,想知道是否有可能删除这个自定义事件发射器。大部分代码来自Pedro Teixeira的Hand on 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);
})();

2 个答案:

答案 0 :(得分:6)

您需要使用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);
})();

答案 1 :(得分:3)

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*/])