javascript - emit() 和 on() 不起作用

标签 javascript node.js

我正在学习nodejs,出现了一些问题,emit()和on()不是一个函数..

这是我的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();
        });
    }
}

这是我的 app.js 文件

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

这是错误 类型错误:Emitter.on 不是一个函数

当我实例化发射器时: varemitter = new Emitter();

这是错误: 类型错误:发射器不是构造函数 然后,我使用以下文字语法导出模块: module.exports= {emit: 发射} 仍然出现错误,new Emitter() is not a constructor

所以,我用这个导出它: module.exports = Emitter; 而不是使用这种模式module.exports = {emit: Emitter},我仍然不知道为什么我不能用文字导出它,知道吗?

最佳答案

您已经创建了一个类。使用new Emitter() 创建它的实例。此外,您还必须导出和导入 Emitter 类:

// 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');

每当您将 new 运算符与构造函数一起使用时,都会创建一个新对象。该对象的原型(prototype)将是构造函数的 prototype 属性。然后,使用新对象调用构造函数(构造函数中的 this 就是新对象)。

关于javascript - emit() 和 on() 不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45275379/

相关文章:

node.js - Node/Express & Postgresql - 当没有行匹配时

javascript - 如何阻止简单的 Discord 机器人 ping 用户?

javascript - .js 文件中的变量不会保留 AJAX 的值

Javascript 字符串验证。如何在字符串中只写一次字符并且只在开头?

javascript - NodeJS全局变量是否绑定(bind)到 "module"函数?

javascript - promise 以不同的方式执行时显示不同的结果

javascript - Google map - 使用 MVC 对象填充 map

javascript - 添加回调函数时 phantomJS click() 不起作用

javascript - Nodejs/JavaScript 模块加载和引用

javascript - 以更好的方式破坏和设置值