EventEmitter中正确删除事件监听器

EventEmitter中正确删除事件监听器

本文介绍了如何在Node JS EventEmitter中正确删除事件监听器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个GET和POST路由的设置,其想法是将POST路由到该路由会触发一个事件,而GET路由是一个服务器发送的事件流,每次触发POSTed事件时都会触发...但是,我认为我做错了,因为尽管只有一个事件流订阅者,但事件监听器似乎还是被例行添加了……我在做什么错了?

I have a set up with a GET and a POST route, the idea being that POSTing to the route triggers an event, and the GET route is a server-sent eventstream which fires each time the POSTed event is triggered... however, i think i've done something wrong as event listeners seem to get added routinely despite only having one event stream subscriber... what am i doing wrong?

var events = require('events'),
EventEmitter = events.EventEmitter,
rr = new EventEmitter();

app.post('/api/:boardname/remoterefresh', function(req, res){
    var boardname = req.param('boardname'),
    data = new Date().getTime();
    rr.emit("refresh-"+boardname, data)
    res.json({data: data})
});

app.get('/api/:boardname/remoterefresh', function(req, res){
    var boardname = req.param('boardname')

    rr.on("refresh-"+boardname, function(data){
        setTimeout(function(){
            res.write('data: '+data+'\n\n');
        }, 1000)
    });

    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, function(){
            //
        })
    })

})

推荐答案

您应命名附加为事件处理程序的函数.然后在删除它时,只需按名称传递函数即可:

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);
    });
});

基本上, removeListener 将通过引用查找给定的函数,如果发现该函数会将其从事件处理程序中删除.

Basically removeListener will look up the given function by reference, if it found that function it will remove it from the event hander.

这篇关于如何在Node JS EventEmitter中正确删除事件监听器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-03 13:32