I have node.js app with socket.io which I use to select and load different external modules (which I call "activities") in real time.
Since every module binds it's own events to the sockets, when I change from one module to another I want to be able to remove from my sockets all the event listeners that the previous module added.
I would use emitter.removeAllListeners(), but that would also remove the events I define in the server, which I do not want.
Here is how my code looks like:
app.js
// Boilerplate and some other code var currentActivity; io.sockets.on('connection', function(client){ client.on('event1', callback1); client.on('event2', callback2); client.on('changeActivity', function(activityPath){ var Activity = require(activityPath); currentActivity = new Activity(); // Here I'd like some loop over all clients and: // 1.- Remove all event listeners added by the previous activity // 2.- Call currentActivity.bind(aClient) for each client }); }) An example activity would be something like the following
someActivity.js
module.exports = function(){ // some logic and/or attributes var bind = function(client){ client.on('act1' , function(params1){ // some logic }); client.on('act2' , function(params2){ // some logic }); // etc. } } So, for instance in this example, if I change from someActivity.js to some other activity, I'd like to be able to remove for all clients the listeners for "act1" and "act2", without removing the ones for "event1", "event2" and "changeActivity".
Any idea on how to accomplish this?
newListenerevent, or pssibly (b) get the listeners for the events you want to keep withemitter.listeners()for the events you want to keep, clear all else, and reattach them (never tried it, might have side effects).