Tuesday, June 4, 2024
 Popular · Latest · Hot · Upcoming
40
rated 0 times [  47] [ 7]  / answers: 1 / hits: 7535  / 11 Years ago, thu, january 2, 2014, 12:00:00

From the nodejs source code (LOC 179), we have the following:



EventEmitter.prototype.once = function(type, listener) {

/** ... **/

function g() { /** ... **/ }

g.listener = listener; // => ???
this.on(type, g);

return this;
};


So far, my thinking goes like this:



EventEmitter.once() sets an event of type and removes it immediately once the callback listener has been called via the g(). But what really does the line g.listener = listener; do?



Does it add a property listener which is a function to the function object created by the constructor g() at the time of invocation?


More From » node.js

 Answers
9

It is set so that you can later call removeListener.



If you call this.once(event, listener) and later call this.removeListener(listener), the code will not find listener in the list because it is wrapped inside g.



That's why the test at L214 does:



 if (list === listener ||
(util.isFunction(list.listener) && list.listener === listener)) {

[#49065] Wednesday, January 1, 2014, 11 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
adilene

Total Points: 395
Total Questions: 88
Total Answers: 109

Location: Indonesia
Member since Tue, Aug 3, 2021
3 Years ago
;