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?
Both the browser and Node. js use JavaScript as their programming language. Building apps that run in the browser is a completely different thing than building a Node. js application.
EventEmitter Class When an EventEmitter instance faces any error, it emits an 'error' event. When a new listener is added, 'newListener' event is fired and when a listener is removed, 'removeListener' event is fired. EventEmitter provides multiple properties like on and emit.
Thanks to some creative engineers, it is now feasible to use Node. js modules in browsers, but not directly. Being able to call Node. js modules from JavaScript running in the browser has many advantages because it allows you to use Node.
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');
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With