解除Node.js中的事件
以stdin.on
为例。 callbackstdin.on
堆栈,所以如果我写(在CoffeeScript中)
stdin = process.openStdin() stdin.setEncoding 'utf8' stdin.on 'data', (input) -> console.log 'One' stdin.on 'data', (input) -> console.log 'Two'
那么每当我在提示符下按回车,我都会得到
One Two
我的问题是,有没有什么办法删除/replacecallback一旦绑定? 或者是自己绑定代理callback和pipe理状态的唯一方法?
您可以使用removeListener(eventType, callback)
来移除一个事件,该事件应该适用于各种发射器。
来自API文档的示例:
var callback = function(stream) { console.log('someone connected!'); }; server.on('connection', callback); // ... server.removeListener('connection', callback);
所以你需要一个variables来保存对callback的引用,因为很明显,不可能知道你想要删除哪个callback。
编辑
在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'
请参阅: http : //nodejs.org/docs/latest/api/events.html#emitter.removeListener
或者你可以使用:
stdin.once
而不是stdin.on