Pages

2013-01-30

Node.js: Inheriting from Node Event Emitter


If you are interested in using Node’s event emitter pattern throughout your application, you can create a pseudo-class and make it inherit from EventEmitter like this:


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

// Here is the MyClass constructor:

var MyClass = function() {}util.inherits(MyClass, EventEmitter);
By creating a class that inherits from EventEmitter, instances of MyClass can emit events:


MyClass.prototype.someMethod = function() {this.emit("custom event", "argument 1", "argument 2");};
Here, when the someMethod method is called on an instance of MyClass, the example emits an event
named custom event. The event also emits some data, in this case two strings: "argument 1" and
"argument 2". This data will be passed along as arguments to the event listeners.


Clients of MyClass instances can listen to the event named custom event like this:
var myInstance = new MyClass();myInstance.on('custom event', function(str1, str2) {console.log('got a custom event with the str1 %s and str2 %s!', str1, str2);});
For example, you could build a pseudo-class named Ticker that emits a “tick” event every second: 

var util = require('util'),EventEmitter = require('events').EventEmitter;var Ticker = function() {var self = this;setInterval(function() {self.emit('tick');}, 1000);};util.inherits(Ticker, EventEmitter);

Clients of this class could instantiate this Ticker class and listen for the “tick” events like so:
var ticker = new Ticker();ticker.on("tick", function() {console.log("tick");});





No comments:

Post a Comment