开发者

node.js remove event listener not working

开发者 https://www.devze.com 2023-03-06 08:47 出处:网络
I\'m trying to remove some eventlistener like this: var callback = function () { someFun(someobj) } console.log(c开发者_运维知识库allback)

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

精彩评论

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