view raw
exebook exebook - 11 months ago 43
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)
} = 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 =;

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


The issue is that your entire code is synchronous.

As part of calling, 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() {