Nodejs / Typescript: Using EventEmitter between multiple classes

232 Views Asked by At

I am using tsyringe as a dependency container and I have 2 classes. AccountingService and TransactionService. I am listening to the event triggered in TransactionService so that I can update the data in AccountingService using accountingRepository but on the method of updateTriggered, it shows an error Cannot read properties of undefined (reading 'findOne') on accountingRepository. Here is how my class look like:

AccountingService

@injectable()
class AccountingService {
 constructor(
   private accountingRepository: AccountingRepository,
   private transactionService: TransactionService
 ) {
    this.transactionService.on('updateTrigger', this.updateTrigger);
}

private async updateTrigger(data: any) {
   this.accountingRepository.findOne({ id: data.id })
}
}

TransactionService:

@injectable()
    class TransactionService extends EventEmitter {
     constructor(
       ...Some dependencies,
     ) {}
    
    private async someTransactionOccurred(data: any) {
       this.emit('updateTrigger', 'id', {});
    }
    }

console.log(this) in updateTrigger method is showing TransactionService object instead of AccountingService

1

There are 1 best solutions below

2
On

Okay I found the solution. Changing it from

this.transactionService.on('updateTrigger', this.updateTrigger);

to:

this.transactionService.on('updateTrigger', this.updateTrigger.bind(this));

solved it. So, what I understand is that, it will be the object of transactionService if we dont explicitly use .bind(this). Although, I am still waiting for the expert why is like this