Is There Any Eventemitter In Browser Side That Has Similar Logic In Nodejs?
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:
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
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?"