开发者

node.js remove event listener not working

I'm trying to remove some eventlistener like this:

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

    console.log(c开发者_运维知识库allback)

    e.once("5", callback);

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

But it doesn't work.

The first console log shows:

[Function]

The second one shows:

[Function: g]

Why are they different?


The implementation of once() inserts a function g() to remove your listener after one call.

From 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;
};

So, if you did this:

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

they'd be the same.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜