Sunday, 1 April 2012

Node.js: EventEmitter and Observer pattern


The EventEmitter is the base building block for all compositions that would need to broadcast data to multiple consumers. Whenever there is an object that represents the source of several kinds of events, node.js usually makes the underlying class inherit from EventEmitter. The EventEmitter implementation makes use of the observer pattern by providing the ‘on’ function for objects that are interested in listening to an event. For e.g. you can listen to a specific event by calling the 'on()' function on your object, providing the name of the event, as well as a callback closure as the parameters.
eventEmitterInstance.once('event', callbackSample1); //singular callback registration
//or
eventEmitterInstance.on('event', callBackSample2); //multiple callback

Below given is a sample server implementation that logs the messages passed as querystring to the server using the EventEmitter implementation

var http = require('http');
var port = process.env.PORT;

var server = http.createServer(function(request, response){
       
    var eventEmitter = require('events').EventEmitter;
    var eventEmitterInstance = new eventEmitter();
   
    var querystring = require('querystring');
    var message = querystring.parse(request.url).message;
   
    var callbackSample1 = function(message)
    {
        console.log('logging from 1st callback function ' + message);
    };
   
    var callBackSample2 = function(message)
    {
        console.log('logging from 2nd callback function ' + message);
    };
       
    eventEmitterInstance.once('event', callbackSample1); //singular callback registration
    eventEmitterInstance.emit(message);
       
    eventEmitterInstance.on('event', callBackSample2); //multiple callback
    eventEmitterInstance.emit(message);
    eventEmitterInstance.emit(message);
   
   
    eventEmitterInstance.removeListener('event', callBackSample2);
   
    response.writeHead(200);
    response.end('<html>'+
                    '<head>'+
                        '<meta http-equiv="Content-Type" content="text/html; '+
                        'charset=UTF-8" />'+
                    '</head>'+
                    '<body>'+
                    '<form method="post">' +
                         '<h1>Messaging sample </h1>' +
                    '</form>'+
                    '</body>'+
                    '</html>');
   
});
server.listen(port);
console.log('Server started....');

As you can see, the on() function returns a reference to the object it belongs to, allowing you to chain several of such event listeners.  If you're only interested in the first occurrence of an event, you can use the once() function instead. Finally, you can remove event listeners by using the removeListener function.

No comments:

Post a Comment