Stopping an event listener after a condition

I have some code similar to this:

emitter.on('request', request => {
    if(condition) doSomething(request);
});

function doSomething(request){
    emitter.on('message', message => {
        if(anotherCondition){
            //
            //Some code to send something
            //
        }
    })
}

      

Basically, if it's unclear, I try to have the listener wait for the request and then send back everything and wait for the recipient to respond to what I sent. However, when this happens, the listener on('message'

is still active, and the next request the emitter receives sends everything twice . Next time he will send all three times. How can I safely stop this?

+3


source to share


1 answer


You can observe from your code that you are creating a new listener every time you call doSomething (). So the number of times you receive a message increases every time you call doSomething ()

You must define emitter.on ('message' .... block outside doSomething () and instead just emit an emit ('message' ... inside doSomething ()) event to emit the event or use removeListener ('message ... . to disable the emitter of the event under certain circumstances.



If you maintain 1 emitter and 1 listener at all times, you should be fine.

Basically this should be what you expect.

+1


source







All Articles