Is there any EventEmitter in browser side that has similar logic in nodejs?

It is so easy to use eventEmitter in node.js:

var e = new EventEmitter();
e.on('happy', function(){console.log('good')});
e.emit('happy');

Any client side EventEmitter in browser native?


In modern browsers, there is EventTarget.

class MyClass extends EventTarget {
  doSomething() {
    this.dispatchEvent(new Event('something'));
  }
}

const instance = new MyClass();
instance.addEventListener('something', (e) => {
  console.log('Instance fired "something".', e);
});
instance.doSomething();

Additional Resources:

  • Maga Zandaqo has an excellent detailed guide here: https://medium.com/@zandaqo/eventtarget-the-future-of-javascript-event-systems-205ae32f5e6b

  • MDN has some documentation: https://developer.mozilla.org/en-US/docs/Web/API/EventTarget

  • Polyfill for Safari and other incapable browsers: https://github.com/ungap/event-target


There is a NPM package named "events" which makes you able to make event emitters in a browser environment.

const EventEmitter = require('events')
 
const e = new EventEmitter()
e.on('message', function (text) {
  console.log(text)
})
e.emit('message', 'hello world')

in your case, it's

const EventEmitter = require('events')

const e = new EventEmitter();
e.on('happy', function() {
    console.log('good');
});
e.emit('happy');