Home > other >  EventEmitter - Could not listen an Event
EventEmitter - Could not listen an Event

Time:04-06

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!

CodePudding user response:

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);
…
  • Related