参考



普通に使う

var events = require('events');

var foo = new events.EventEmitter();

foo.on('bar', function(data){
console.log(data.message + ' - ' + data.date);
});

foo.emit('bar', {message : 'hello', date : new Date()});
foo.emit('bar', {message : 'helloooooo', date : new Date()});

hello - Tue Jul 24 2012 18:01:48 GMT+0900 (JST)
helloooooo - Tue Jul 24 2012 18:01:48 GMT+0900 (JST)


クラスに組み込む

クラスにevents.EventEmitter.callとutil.inheritsすると、インスタンスにon/emitが追加される

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

var User = function(name){
events.EventEmitter.call(this);
this.name = name;
}
util.inherits(User, events.EventEmitter);

var shokai = new User('shokai');
var ahokai = new User('ahokai');

var callback = function(data){
console.log(this.name+' => '+data);
};

shokai.on('hungry', callback);
ahokai.on('hungry', callback);

shokai.emit('hungry', 'kazusuke');
ahokai.emit('hungry', 'zanmai');

shokai => kazusuke
ahokai => zanmai