Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Nodejs removing event listeners

Tags:

node.js

Looking to get some help. I'm new to Nodejs and wondering if it is possible, to remove this custom event emitter. Most of this code comes from the Hand on nodejs by Pedro Teixeira. My function at the bottom is attempting to remove the custom event emitter you setup in the book.

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);
})();
like image 706
JeffH Avatar asked Apr 15 '12 18:04

JeffH


Video Answer


1 Answers

You need to use removeListener method of ticker object, not EventEmitter. The first argument is event name, the second - link to event listener to be deleted.

This code should works:

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);
})();
like image 63
Vadim Baryshev Avatar answered Oct 03 '22 15:10

Vadim Baryshev