Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

209
Views
EventEmitter - Could not listen an Event

Everyone.

I'm trying to apply observer pattern in my app. But, the problem is subscribers can not listen event. When a function(useEvent.js) fired event, nothing happened. Written below is my codes.

payment.js

const EventEmitter = require('events')


class PaymentEvent extends EventEmitter {
    getPaid(paymentId) {
        this.emit('create', paymentId)
        console.log('Created')
    }
}


module.exports = PaymentEvent

subscriber.js

const PaymentEvent = require('./payment')
const payment = new PaymentEvent()
payment.on('create', paymentId => {
    console.log('Event Fired!!!')})

// Expected : 'Event Fired!!!'
// Result : Nothing happened
...

useEvent.js

const PaymentEvent = require('./payment')

const createPayment = async data => {
    const payment = await CorePayment.create(data)
    const paymentId = payment.id
    const paymentEvent = new PaymentEvent()
    
    // This parts of code will fire event! 
    paymentEvent.getPaid(paymentId)
    return paymentId
}
...

Thank you very much in advance!

over 4 years ago · Santiago Trujillo
1 answers
Answer question

0

As already pointed out in the comment, you're creating multiple instances of PaymentEvent, which means you create multiple, different, event emitters.

Instead, you can instantiate PaymentEvent in payment.js and import the resulting instance when you need it:

// payment.js
…
module.exports = new PaymentEvent;

// subscriber.js
const paymentEvent = require('./payment');
paymentEvent.on(…)

// useEvent.js
const paymentEvent = require('./payment');
…
paymentEvent.getPaid(paymentId);
…
over 4 years ago · Santiago Trujillo Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!