2011-05-14 55 views
0

我想删除一些事件侦听这样的:node.js中移除事件监听器不工作

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

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); 

他们会是相同的。

+0

谢谢,看起来像我遇到了一个错误。我应该从这个愚蠢的旧版本升级... – Harry 2011-05-14 11:25:52