Search code examples
node.jseventemitter

has no method of emit in node.js


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();

Solution

  • 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');
    };