简体   繁体   中英

Why can't I capture events from an extended EventEmitter class in Node.js?

I've been banging my head against why I can't capture events emitted from this code in Node.js. My gut feeling is something is out of scope, but I can't figure out what it is. The console.log line of code in index.js never gets executed. Is my event not being emitted?

player.js

const EventEmitter = require('events').EventEmitter;

class rocketPlayer extends EventEmitter {
  constructor(options) {
    super(options);
  }

  update(connection) {
    //do some logic with playlists
    this.play(connection);
  }

  play(connection) {
    // do some stuff
    this.emit('nowPlaying',song.title);
  }
}

module.exports = rocketPlayer

index.js

const rocketPlayer = require('./player.js');
const player = new rocketPlayer();

player.on('nowPlaying', title => {
  console.log('caught nowPlaying event');
});

//define a connection
player.update(connection)

you have a few typos: You are missing a bracket after your listener. You also don't pass the constructor arguments down to the super constructor properly. Following code works for me:

const EventEmitter = require('events').EventEmitter;

class rocketPlayer extends EventEmitter {
  constructor(options) {
    super(options);
  }

  update(connection) {
    //do some logic with playlists
    this.play(connection);
  }

  play(connection) {
    // do some stuff
    this.emit('nowPlaying', 'song.title');
  }
}

const player = new rocketPlayer();

player.on('nowPlaying', title => {
  console.log('caught nowPlaying event');
}); // <= fixed missing bracket

//define a connection
player.update('connection');

Note: as you didn't define song i just converted it into a string

I think you had a few things wrong with your example as posted; notably the song method as written was throwing an exception.

player.js:

"use strict";
let EventEmitter = require('events').EventEmitter;

class RocketPlayer extends EventEmitter {
  constructor(options) {
    super(options);
  }

  update(connection) {
    //do some logic with playlists
    this.play(connection);
  }

  play(song) {
    // do some stuff
    this.emit('nowPlaying', song.title);
  }
}

module.exports = RocketPlayer;

index.js:

const RocketPlayer = require('./player.js');
const player = new RocketPlayer();

const connection = {title: "Boooboo!"};

player.on('nowPlaying', title => {
  console.log('caught nowPlaying event', title);
});

//define a connection
player.update(connection);

result:

PS D:\Code\data> node -v
v7.4.0
PS D:\Code\data> node ./index
caught nowPlaying event Boooboo!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM