Gilbert Comeau
Gilbert Comeau

Reputation: 33

NodeJS: Cannot call method 'push' of undefined

Greenhorn here trying to setup a basic nodejs program using events. My program seems to be fine but I am receiving an error that the push function is undefined. I was under the impression that this is a built-in function. Can someone point me in the right direction? Code is below.

//emitter.js file

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


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


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


module.exports = Emitter;



// app.js file

var Emitter = require('./emitter');


var emtr = new Emitter();

emtr.on('greet', function() {
  console.log('Somewhere, someone said hello');
})

emtr.on('greet', function() {
  console.log('A second greeting occurred');
})


emtr.emit('greet');

Upvotes: 0

Views: 101

Answers (1)

peteb
peteb

Reputation: 19428

You have a mistake in your Emitter.prototype.on() logic.

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

In the above function this.events = this.events[type] || []; is incorrect because it is reassigning the entire events object to an array. Which means that the following line this.events[type].push(listener) won't be an array but undefined.

Just correct your function to properly assign this.events[type]

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

Upvotes: 3

Related Questions