javascript - 尝试在类内调用发射方法时,从 EventEmitter 扩展的类上未定义的“this”
问题描述
我正在尝试使用自定义事件发射器来处理 webhook,但是当从我的类中调用方法时,我总是将 'this' 设为未定义
服务Webhook.js
class WebhookHandler extends EventEmitter{
constructor (){
super();
}
receiver(req, res){
try {
res.sendStatus(200);
if (req.body && req.body.action) {
this.emit(req.body.action, req.body)
}
} catch (error) {
console.log(error)
}
}
}
module.exports = {
WebhookHandler: WebhookHandler
}
index.js
var webhookh = new serviceWebhook.WebhookHandler();
router.post('/webhookendpoint', webhookh.receiver);
webhookh.on('action_one', function name(message) {
console.log('EMITTED')
console.log(message)
}
这是我得到的错误:
TypeError:无法读取未定义的属性“发出”
我也试过这个:
super.emit(req.body.action, req.body)
但后来我得到这个错误:
TypeError:无法读取未定义的属性“_events”
解决方案
将 WebhookHandler 类实例的接收器方法传递给路由器的回调会移动该方法的词法范围。尝试:router.post('/webhookendpoint', webhookh.receiver.bind(webhookh));
这会将回调中 this 的范围绑定到您的 WebhookHandler 实例的范围。
推荐阅读
- python - 读取python数据框,一列表示为字符串
- spring-boot - Spring Boot - JPA 规范返回的展平 JSON 实体以导出到 excel
- python - Python 问题创建定义以合并两个数据集 - 使用字符串来引用和 vars()
- node.js - 猫鼬回调不执行
- salesforce - Lightning Experience 专家 - 步骤 6 - 无法完成
- spring - https//recipe-010-webhook.herokuapp.com?op=webhook .Error - Invalid URI: The URI scheme is not valid
- angular - angular 9 数组在订阅方法中为空
- excel - 将 Excel 值传递给同一类的多个方法
- javascript - JS倒数计时器停止在0
- firefox - 无法从 Firefox 中的 PeerConnection 检索 RTCVideoSourceStats