2011-05-14 54 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