Martin Thompson
Martin Thompson

Reputation: 3745

How to Capture events / Listen / Observe to events emitted from Inner functions in nodejs?

I would like to run a bunch of code within functions - and functions called within those functions and "bubble" the events up without too much work.

Note: I am trying to move away from OOP, more into functional programming so I can't use the class implements eventemitter. I am not sure if I have to

obj2.ts

import {EventEmitter} from 'events'

export async function obj2(){
    const ev = new EventEmitter()
    ev.emit('test','Yahoo!')
    await new Promise(r => setTimeout(r, 2000));
    ev.emit('test2','Yahoo! - second time')
    ev.emit('test','Yahoo!')
    await new Promise(r => setTimeout(r, 10000));
    ev.emit('test2','Yahoo! - third time')
}

obj1.ts

import {EventEmitter} from 'events'
import { inherits } from 'util'
import {obj2} from './obj2'

async function obj1(){
     await obj2()    
}

inherits(obj1, EventEmitter)

export {obj1}

index.js ( entry point )

import {obj1} from './obj1'

obj1.on('test', () => { // << this doesn't work obviously 
    //console.log(this)
    console.log('**')
})

obj1()

Upvotes: 0

Views: 587

Answers (1)

eol
eol

Reputation: 24565

Not sure why you'd need obj1 - you can just export the EventEmitter from obj2 and listen on the returned object:

in obj2.js:

import {EventEmitter} from 'events'

export const obj2EventEmitter = new EventEmitter();
export async function startEmitting(){
    obj2EventEmitter.emit('test','Yahoo!')
    await new Promise(r => setTimeout(r, 2000));
    obj2EventEmitter.emit('test2','Yahoo! - second time')
    obj2EventEmitter.emit('test','Yahoo!')
    await new Promise(r => setTimeout(r, 10000));
    obj2EventEmitter.emit('test2','Yahoo! - third time')
}

in your index.js:

import {obj2EventEmitter, startEmitting} from './obj2';

obj2EventEmitter.on('test', () => {
    console.log('**')
});

(async () => {
    await startEmitting();
})()

Upvotes: 0

Related Questions