Node.js EventEmitter`on`事件未响应`emit`操作

时间:2019-03-16 12:14:09

标签: javascript node.js eventemitter

我有一个代表教室的Node.js应用。我正在使用Node版本11.11.0。这个程序有两个文件:index.js和student.js。相关代码如下:

index.js

const EventEmitter = require('events');
const Student = require('./student');

async function start() {
  eventEmitter.on('newListener', (event, listener) => {
     console.log(`Added ${event} listener.`);
  });

  eventEmitter.on('handRaised', (question) => {
    console.log(question);
  });

  for (let i=0; i<10; i++) {
    let student = new Student(`Student #${i+1}`);
    student.attend();
  }
}

start();

student.js

'use strict';

const EventEmitter = require('events');

class Student {
  constructor(name) {
    this.name = name;
  }

  attend() {
    // simulate a student randomly asking a question within 10 minutes
    let minutes = (Math.floor(Math.random() * 10) + 1) * 60000;
    setTimeout(function() {
      EventEmitter.emit('handRaised', 'What is the 2 + 3?');
    }, minutes);
  }
}

module.exports = Student;

运行此命令时,出现错误消息EventEmitter.emit is not a function。我尝试了几种变体,没有任何运气。我在做什么错了?

2 个答案:

答案 0 :(得分:2)

您不能直接在emit上使用EventEmitter。您需要有一个实例。例如:

const eventEmitter = new EventEmitter();
// Now, you're okay to go with emit
eventEmitter.emit('handRaised', 'What is the 2 + 3?');

要使用同一实例,请在文件中定义它,并在需要使用它的任何地方提出要求。然后,您可以放心使用onemit

答案 1 :(得分:0)

@Bhojendra Rauniyar给出的答案是正确的,恕我直言,但缺少下面的工作示例。请注意,我做了一个微妙但重要的更改,我为setTimeout()中的student.js定义了回调函数:我使用的是绑定学生实例的() =>的箭头函数this到回调函数。这是从回调函数调用实例变量所必需的。另外,也可以使用function () { ... }.bind(this)

index.js

const EventEmitter = require('events');
const Student = require('./student');
const eventEmitter = new EventEmitter();

async function start() {
  eventEmitter.on('newListener', (event, listener) => {
    console.log(`Added ${event} listener.`);
});

  eventEmitter.on('handRaised', (question) => {
    console.log(question);
});

  for (let i=0; i<10; i++) {
    let student = new Student(`Student #${i+1}`, eventEmitter);
    student.attend();
  }
}

start();

student.js

'use strict';

class Student {
  constructor(name, eventEmitter) {
    this.name = name;
    this.eventEmitter = eventEmitter;
  }

  attend() {
    // simulate a student randomly asking a question within 10 minutes
    let minutes = (Math.floor(Math.random() * 10) + 1) * 60000;
    setTimeout(() => {
      this.eventEmitter.emit('handRaised', 'What is the 2 + 3?');
  }, minutes);
  }
}

module.exports = Student;