How to properly remove event listeners in node js eventemitter
To avoid referencing the anonymous listener callback function, you can dangerously wipe registered listeners with the emitter.removeAllListeners method:
rr.removeAllListeners("refresh-"+boardname)
Be aware that this approach can easily result in unintended side-effects (deregistering listeners registered elsewhere in the codebase), and should be reserved for "wipe the slate clean" use cases (eg: Testing)
You should name the function you attach as event handler. Then on removing it, you just pass the function by name:
app.get('/api/:boardname/remoterefresh', function(req, res){
var boardname = req.param('boardname')
function refreshHandler(data){
setTimeout(function(){
res.write('data: '+data+'\n\n');
}, 1000)
}
rr.on("refresh-"+boardname, refreshHandler);
req.socket.setTimeout(Infinity);
res.writeHead(200, {
'Content-Type': 'text/event-stream',
'Cache-Control': 'no-cache',
'Connection': 'keep-alive'
});
res.write('\n');
req.on('close', function(){
console.log('closed')
rr.removeListener("refresh-"+boardname, refreshHandler);
});
});
Basically removeListener
will look up the given function by reference, if it found that function it will remove it from the event hander.