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.
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.
Share Improve this question asked Sep 30, 2015 at 21:19 Martin VrábelMartin Vrábel 9002 gold badges14 silver badges37 bronze badges2 Answers
Reset to default 8You 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');
An eventEmitter supports multiple event handlers. It does not have a mechanism for "replacing" an event handler. As such, you have a couple options:
- You can keep a flag for whether the event handler is already set.
- 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());
};
}