[英]Undefined 'this' on class extending from EventEmitter when trying to call emit method inside of class
I'm trying to use a custom event emitter to handle a webhook, but when calling a method from my class I always get 'this' as undefined 我正在尝试使用自定义事件发射器来处理Webhook,但是从类中调用方法时,总是得到“ this”未定义
serviceWebhook.js 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 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)
}
This is the error I get: 这是我得到的错误:
TypeError: Cannot read property 'emit' of undefined TypeError:无法读取未定义的属性“ emit”
I have also tried this: 我也尝试过这个:
super.emit(req.body.action, req.body)
But then I get this error: 但是然后我得到这个错误:
TypeError: Cannot read property '_events' of undefined TypeError:无法读取未定义的属性“ _events”
Passing the receiver method of an instance of your WebhookHandler class to the callback of your router moves the lexical scope of the method. 将WebhookHandler类的实例的receive方法传递给路由器的回调将移动该方法的词法范围。 Try:
router.post('/webhookendpoint', webhookh.receiver.bind(webhookh));
试试:
router.post('/webhookendpoint', webhookh.receiver.bind(webhookh));
This will bind the scope of this within the callback to that of your instance of WebhookHandler. 这会将回调的范围绑定到您的WebhookHandler实例的范围。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.