Q:

emit() and on() not working

i'm learning nodejs and some issues appeared, that emit() and on() is not a function..
here's my emitter.js fie

   function Emitter(){
    this.events = {};
}

Emitter.prototype.on = function(type, listener){
    this.events[type]=this.events[type]||[];
    this.events[type].push(listener);
}

Emitter.prototype.emit = function(type){
    if (this.events[type]) {
        this.events[type].forEach(function(listener){
            listener();
        });
    }
}

and here's my app.js file

//Emitter
var Emitter = require('./emitter');
Emitter.on('greet', function(){
    console.log('a greeting occured!`');
});
console.log('hello');
Emitter.emit('greet');

and here's the error
TypeError: Emitter.on is not a function
when i instantiated the Emitter:
var emitter = new Emitter();
and this the error:
TypeError: Emitter is not a constructor
then, i export the modules using this literal syntax:
module.exports= {emit: Emit}
the error still appeared that the new Emitter() is not a constructor
so, i export it with this:
module.exports = Emitter; instead with this pattern module.exports = {emit: Emitter} and i still don't know why i can't export it with literal, any idea?

A:

You've created a class. Create an instance of it using new Emitter(). Also, you have to export and import the Emitter class:

// emitter.js
function Emitter(){
  this.events = {};
}

Emitter.prototype.on = function(type, listener){
  this.events[type]=this.events[type]||[];
  this.events[type].push(listener);
}

Emitter.prototype.emit = function(type){
  if (this.events[type]) {
    this.events[type].forEach(function(listener){
      listener();
    });
  }
}
// Export the Emitter class: module.exports = Emitter;

// app.js
// Import the emitter class: var Emitter = require('./emitter');
var emitter = new Emitter();
emitter.on('greet', function(){
  console.log('a greeting occured!`');
});
console.log('hello');
emitter.emit('greet');

Whenever you use the new operator with a constructor function, a new object is created. The prototype of that object will the prototype property of the constructor function. Then, the constructor is called with the new object (this in the constructor is the new object).

