Unbinding events in Node.js

后端 未结 2 1069
名媛妹妹
名媛妹妹 2021-01-03 19:44

Let\'s take stdin.on as an example. Callbacks to stdin.on stack, so if I write (in CoffeeScript)

stdin = process.openStdin()
stdin.         


        
相关标签:
2条回答
  • 2021-01-03 20:27

    You can use removeListener(eventType, callback) to remove an event, which should work with all kinds of emitters.

    Example from the API docs:

    var callback = function(stream) {
      console.log('someone connected!');
    };
    server.on('connection', callback);
    // ...
    server.removeListener('connection', callback);
    

    So you need to have a variable that holds a reference to the callback, because obviously, it's otherwise impossible to tell which callback you want to have removed.

    EDIT
    Should be someone like this in CS:

    stdin = process.openStdin()
    stdin.setEncoding 'utf8'
    
    logger = (input) -> console.log 'One'
    stdin.on 'data', logger
    stdin.removeListener 'data', logger
    
    stdin.on 'data', (input) -> console.log 'Two'
    

    See: http://nodejs.org/docs/latest/api/events.html#emitter.removeListener

    0 讨论(0)
  • 2021-01-03 20:39

    Or you can use:

    stdin.once instead of stdin.on

    0 讨论(0)
提交回复
热议问题