尝试在类内部调用 emit 方法时,从 EventEmitter 扩展的类上出现未定义的'this'



我正在尝试使用自定义事件发射器来处理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:无法读取未定义的属性

我也尝试过:

super.emit(req.body.action, req.body)

,但是我得到了这个错误:

TypeError:无法读取未定义的

的属性'_events'

将您的Webhookhookhandler类实例的接收器方法传递到路由器的回调中,移动该方法的词汇范围。尝试:router.post('/webhookendpoint', webhookh.receiver.bind(webhookh));这将在回调中将其范围绑定到您的webhookhookhandler实例。

最新更新