[英]Unbinding events in Node.js
Let's take stdin.on
as an example.我们以
stdin.on
为例。 Callbacks to stdin.on
stack, so if I write (in CoffeeScript)回调到
stdin.on
堆栈,所以如果我写(在 CoffeeScript 中)
stdin = process.openStdin()
stdin.setEncoding 'utf8'
stdin.on 'data', (input) -> console.log 'One'
stdin.on 'data', (input) -> console.log 'Two'
then every time I hit return at the prompt, I get然后每次我在提示下按回车时,我都会得到
One
Two
My question is, is there any way to remove/replace a callback once bound?我的问题是,有没有办法删除/替换绑定后的回调? Or is the only approach to bind a proxy callback and manage state myself?
或者是绑定代理回调并自己管理状态的唯一方法?
You can use removeListener(eventType, callback)
to remove an event, which should work with all kinds of emitters.您可以使用
removeListener(eventType, callback)
来删除事件,该事件应该适用于所有类型的发射器。
Example from the API docs: API 文档中的示例:
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:在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请参阅: http : //nodejs.org/docs/latest/api/events.html#emitter.removeListener
Or you can use:或者你可以使用:
stdin.once
instead of stdin.on
stdin.once
而不是stdin.on
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.