首页 > 解决方案 > 尝试在类内调用发射方法时,从 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”

标签: javascriptnode.js

解决方案


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


推荐阅读