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

十年热恋 提交于 2021-02-06 06:50:40

问题


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?


回答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:

  • 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




回答2:


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




回答3:


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




回答4:


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

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

in your case, it's

var EventEmitter = require('events')

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



回答5:


I ended up using this:

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

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




回答6:


You need a JavaScript library, like this https://github.com/Olical/EventEmitter?



来源:https://stackoverflow.com/questions/45831911/is-there-any-eventemitter-in-browser-side-that-has-similar-logic-in-nodejs

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!