【发布时间】:2016-05-29 05:13:10
【问题描述】:
当我将函数注册为事件时,不会调用所述函数内部的发射。它自己的函数被调用(由日志测试)。现在,当我使用方法 2 注册事件时,它可以工作。这是为什么呢?
方法一(不调用事件):
"use strict";
const EventEmitter = require("events");
class DiscordBot extends EventEmitter{
constructor(key){
super();
}
startBot(){
var self = this;
this.bot.on("ready",self.botReady);
}
botReady(){
var self = this;
self.emit("Bot_Ready");
console.log("TESD");
}
}
方法2(有效):
"use strict";
const EventEmitter = require("events");
class DiscordBot extends EventEmitter{
constructor(key){
super();
}
startBot(){
var self = this;
this.bot.on("ready",function () {
self.botReady();
});
}
botReady(){
var self = this;
self.emit("Bot_Ready");
console.log("TESD");
}
}
注册:
bot.on("Bot_Ready", function(){
console.log('this happens ');
});
【问题讨论】:
-
也许你失去了上下文,你需要使用像这样的箭头函数
this.bot.on("ready", () => this.botReady());? -
在您的第一个示例中,是否需要像 self.botReady() 那样调用 self.botReady ?
标签: javascript node.js eventemitter