Nodejs Eventemitters

nodejs

Node ships with a simple EventEmitter class that can be included from the 
'events' module:

var EventEmitter = require('events').EventEmitter;

When creating complex classes, it is common to inherit from this EventEmitter 
class to emit events.  This is basically a simple implementation of the 
Observable pattern.

We should never listen to the events of our own class from within it.  It is not 
natural for an object to observe itself.  It often make our code more difficult 
to understand.

We can listen to a specific event by calling the on() function on our object, 
providing the name of the event, as well as the callback.  For example,

var data = '';
req
  .on('data', function(chunk) {
    data += chunk;
  })
  .on('end', function() {
    ...
  });

The on() function also returns a reference to the object it belongs to, allowing 
us to chain several of such event listeners.

If we only interest in the first occurrence of an event, we can use the once() 
function.

We can remove event listeners by using the removeListener function.  The 
argument to this function is a reference to the callback that you are trying 
to remove, not the name of the event:

var onData = function(chunk) {
  req.removeListener(onData);
};

req.on('data', onData);
Unless otherwise stated, the content of this page is licensed under Creative Commons Attribution-ShareAlike 3.0 License