簡體   English   中英

node.js刪除事件偵聽器不起作用

[英]node.js remove event listener not working

我試圖刪除這樣的事件監聽器:

    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]

他們為什么不同?

執行一次one()會插入一個函數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);

他們會是一樣的。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM