node.js删除事件侦听器无法正常工作

时间:2011-05-14 10:19:07

标签: javascript events node.js

我正在尝试删除这样的eventlistener:

    var callback = function () {
      someFun(someobj)
    }

    console.log(callback)

    e.once("5", callback);

    uponSomeOtherStuffHappening('',
    function() {
      console.log(e.listeners("5")[0])
      e.removeListener(inTurns, callback)
    })

但它不起作用。

第一个控制台日志显示:

[Function]

第二个显示:

[Function: g]

为什么他们不同?

1 个答案:

答案 0 :(得分:1)

once()的实现在一次调用后插入一个函数g()来删除你的监听器。

来自events.js:

EventEmitter.prototype.once = function(type, listener) {
  if ('function' !== typeof listener) {
    throw new Error('.once only takes instances of Function');
  }

  var self = this;
  function g() {
    self.removeListener(type, g);
    listener.apply(this, arguments);
  };

  g.listener = listener;
  self.on(type, g);

  return this;
};

所以,如果你这样做了:

console.log(e.listeners("5")[0].listener);

他们是一样的。

相关问题