![](/img/trans.png)
[英]When extending “eventEmitter” to my class using “super”, this.name returns undefined
[英]Undefined 'this' on class extending from EventEmitter when trying to call emit method inside of class
我正在尝试使用自定义事件发射器来处理Webhook,但是从类中调用方法时,总是得到“ this”未定义
serviceWebhook.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:无法读取未定义的属性“ emit”
我也尝试过这个:
super.emit(req.body.action, req.body)
但是然后我得到这个错误:
TypeError:无法读取未定义的属性“ _events”
将WebhookHandler类的实例的receive方法传递给路由器的回调将移动该方法的词法范围。 试试: router.post('/webhookendpoint', webhookh.receiver.bind(webhookh));
这会将回调的范围绑定到您的WebhookHandler实例的范围。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.