Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How Nodejs EventEmitter.once() work?

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?

like image 648
gmajivu Avatar asked Jan 02 '14 10:01

gmajivu


1 Answers

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)) {
like image 139
Laurent Perrin Avatar answered Sep 23 '22 21:09

Laurent Perrin