js中取消绑定事件

js中取消绑定事件

本文介绍了在Node.js中取消绑定事件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

让我们以 stdin.on 为例。回调 stdin.on 堆栈,所以如果我写(在CoffeeScript)

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

然后每次我在提示符下按回车,我得到

 一个
两个


b $ b

我的问题是,有没有办法删除/替换回调一旦绑定?或者是绑定代理回调并自己管理状态的唯一方法?

解决方案

可以使用 removeListener (eventType,callback)删除一个事件,它应该与各种发射器一起工作。



API文档中的示例:

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

所以你需要一个变量来保存对回调的引用,因为很明显,

EDIT

在CS中应该是这样的人:

p>

  stdin = process.openStdin()
stdin.setEncoding'utf8'

logger =输入)→> console.log'One'
stdin.on'data',logger
stdin.removeListener'data',logger

stdin.on'data',(input) - > ; console.log'Two'

请参阅:


Let's take stdin.on as an example. Callbacks to stdin.on stack, so if I write (in 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.

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

这篇关于在Node.js中取消绑定事件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-03 15:10