0

I made a simple example like below, and I got a error saying 'has no method of 'emit' ', what is the issue ?

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

var Door = function (options) {
    events.EventEmitter.call(this);
}   

util.inherits(Door, EventEmitter);


Door.prototype = {
    open:function(){
       this.emit('open');
    }
}

var frontDoor = new Door('brown');

frontDoor.on('open', function() {
    console.log('ring ring ring');
  });
frontDoor.open();
user824624
  • 7,077
  • 27
  • 106
  • 183

1 Answers1

1

You are replacing the prototype of Door with a new object, which overwrites (/removes) the EventEmitter prototype methods as well:

Door.prototype = {
    open:function(){
       this.emit('open');
    }
}

Instead, just add a single entry to the existing prototype:

Door.prototype.open = function() {
  this.emit('open');
};
robertklep
  • 198,204
  • 35
  • 394
  • 381