exebook exebook - 5 months ago 8
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

on('cooked')
does not fire, why?

var events = require('events');

function Dummy() {
events.EventEmitter.call(this);
}

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)
cb(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) {
console.log('callback')
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

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() {
    cb(a);
  });
}
Comments