Martin Vrábel
Martin Vrábel

Reputation: 900

Socket.IO - How to replace event listener on client

I am wondering if there is an option in Socket.IO client library for Node.js for replacing listener function for specific event.

I have this simple function:

var Service = module.exports = function(address) {
    var _socket = require('socket.io-client')(address);

    this.connectAccount = function(account, callback) {
        _socket.on('account/connected', function (response) {
            callback(response.data, response.message);
        });

        _socket.emit('account/connect', account.getParameters());
    };
}

The problem is, when I call function connectAccount() several times, all anonymous functions I pass each time in on() function get also called and after short while it reaches the limit and throws error.

So my question is if there is a way how to replace each time that listener so each time it gets called only once?

Thanks in advance.

Upvotes: 3

Views: 5190

Answers (2)

jfriend00
jfriend00

Reputation: 707238

An eventEmitter supports multiple event handlers. It does not have a mechanism for "replacing" an event handler. As such, you have a couple options:

  1. You can keep a flag for whether the event handler is already set.
  2. You can remove the listener before you add it. Removing it if it wasn't already set is just a noop.

Code example for only installing the event handler once:

var Service = module.exports = function(address) {
    var initialized = false;
    var _socket = require('socket.io-client')(address);
    this.connectAccount = function(account, callback) {

       if (!initialized) {
            _socket.on('account/connected', function (response) {
                callback(response.data, response.message);
            });
            initialized = true;
        }

        _socket.emit('account/connect', account.getParameters());
    };
}

Upvotes: 2

hassansin
hassansin

Reputation: 17498

You could either remove the listener before attaching new one or check if a listener is attached.

To remove listener:

_socker.removeListener('account/connected', [function]);

To check if an event has listeners:

_socker.hasListeners('account/connected');

Upvotes: 8

Related Questions