exebook exebook -5 years ago 141
Node.js Question

Writing my own event emitter fails

I am trying to write an event emitter, based on this totorial.
But the final event

does not fire, why?

var events = require('events');

function Dummy() {

Dummy.super_ = events.EventEmitter;
Dummy.prototype = Object.create(events.EventEmitter.prototype, {
constructor: {
value: Dummy,
enumerable: false

function _cook(a,cb) {
console.log('frying it',a)

Dummy.prototype.cooking = function(chicken) {
var self = this;
self.chicken = chicken;
self.cook = _cook; // assume dummy function that'll do the cooking
self.cook(chicken, function(cooked_chicken) {
self.chicken = cooked_chicken;
self.emit('cooked', self.chicken);

return self;

var kenny = new Dummy();
fried_chix = {type:'tasty'}

var dinner = kenny.cooking(fried_chix);

dinner.on('cooked', function(chicken) {
console.log('we can eat now!')

Answer Source

The issue is that your entire code is synchronous.

As part of calling kenny.cooking(), the cooked event is emitted (synchronously), but at that point you haven't yet attached a listener for that event.

If you make your _cook method asynchronous, it'll work:

function _cook(a,cb) {
  console.log('frying it',a)
  setImmediate(function() {
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download