Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 737
Xin Avatar asked Aug 23 '17 06:08

Xin


People also ask

Does node js have the same objects as browser based js?

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.

Which is the commonly used events in EventEmitter?

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.

Can you run Nodejs code in browser?

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.


2 Answers

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

like image 172
Brad Avatar answered Oct 19 '22 06:10

Brad


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'); 
like image 31
Amir Gorji Avatar answered Oct 19 '22 07:10

Amir Gorji