简体   繁体   English

尝试在类内调用emit方法时,从EventEmitter扩展的类上的未定义“ this”

[英]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.

相关问题 使用“ super”将“ eventEmitter”扩展到我的类时,this.name返回未定义 - When extending “eventEmitter” to my class using “super”, this.name returns undefined 在CoffeeScript中尝试在类中调用方法(@_methodName)时,它返回undefined - In CoffeeScript when trying to call a method (@_methodName) in a class it returns undefined 是否可以从另一个类内部调用一个类(没有扩展)? - Is it possible to call a class from inside another class (without extending)? NodeJS自定义类扩展了EventEmitter并要求 - NodeJS custom class extending EventEmitter and require 尝试发出自定义类 Vuejs 时,$emit 不起作用 - $emit is not working when trying to emit a custom class Vuejs 类内部未定义的函数调用 - undefined function call inside class 扩展THREE.js“类”时,为什么需要从新对象内调用.call(this)方法? - When extending a THREE.js “class”, why do I need to invoke the .call(this) method from within the new object? 子类中父类的调用方法 - Call method from parent class inside child class 测试类方法内部的静态方法调用时发生TypeError - TypeError when testing static method call inside class method 在扩展类中从异步方法调用超类'异步方法 - Calling super class' async method from async method in extending class
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM