samedi 28 octobre 2017

Getting TypeError 'callback' is not a function on event emitter

I am trying to make this module work on Node 8.7 When I run it, console throws Type Error callback is not a function(on emit method).

I'm using this module with a class in order to make the other class inherit from the Event Emitter.

Node keeps throwing me random errors, when I tried the same code on one file(with Event Emitter and the other class as separate classes) it worked.

//export class EventEmitter...

class EventEmitter{
    constructor(){
        this.events = {};
    }
    on(eventName,callback){
        if (typeof this.events[eventName] !== 'object') {
            this.events[eventName] = [];
        }

        this.events[eventName].push(callback);
    }
    emit(eventName, ...rest) {
        if (this.events[eventName]) {
          this.events[eventName].forEach((callback) => {
            callback(rest);
          });
        } else {
          console.log("The event doesn't exists.");
        }
      }

    off(eventName,callback){
        var index;

            if (typeof this.events[eventName] === 'object') {
                index = this.events[eventName].indexOf(callback);

                if (index > -1) {
                    this.events[eventName].splice(index, 1);
                }
            }
    }
}

module.exports = EventEmitter;

What I'm missing?




Aucun commentaire:

Enregistrer un commentaire