'Nodejs / Typescript: Using EventEmitter between multiple classes

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



Solution 1:[1]

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

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Bellaraus