Skip to content Skip to sidebar Skip to footer

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

Solution 1:

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:


Solution 2:

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');

Solution 3:

Create a customized event in the client, and attach to dom element:

var event = new Event('build');

// Listen for the event.
elem.addEventListener('build', function (e) { /* ... */ }, false);

// Dispatch the event.
elem.dispatchEvent(event);

This is referred from: https://developer.mozilla.org/en-US/docs/Web/Guide/Events/Creating_and_triggering_events Thanks Naeem Shaikh


Solution 4:

This is enough for given case.

class EventEmitter{
    constructor(){
        this.callbacks = {}
    }

    on(event, cb){
        if(!this.callbacks[event]) this.callbacks[event] = [];
        this.callbacks[event].push(cb)
    }

    emit(event, data){
        let cbs = this.callbacks[event]
        if(cbs){
            cbs.forEach(cb => cb(data))
        }
    }
}

Update: I just published little bit more evolved version of it. It is very simple yet probably enough: https://www.npmjs.com/package/alpeventemitter


Solution 5:

I ended up using this:

export let createEventEmitter = () => {
   let callbackList: (() => any)[] = []

   return {
      on(callback: () => any) {
         callbackList.push(callback)
      },
      emit() {
         callbackList.forEach((callback) => {
            callback()
         })
      },
   }
}


Post a Comment for "Is There Any EventEmitter In Browser Side That Has Similar Logic In Nodejs?"