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.

classMyClassextendsEventTarget {
  doSomething() {
    this.dispatchEvent(newEvent('something'));
  }
}

const instance = newMyClass();
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.

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

in your case, it's

constEventEmitter = require('events')

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

Solution 3:

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

varevent = 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.

classEventEmitter{
    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:

exportletcreateEventEmitter = () => {
   letcallbackList: (() => 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?"