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?
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?
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:
MDN documentation:
https://developer.mozilla.org/en-US/docs/Web/API/EventTarget
Maga Zandaqo has an excellent detailed guide on Medium:
https://medium.com/@zandaqo/eventtarget-the-future-of-javascript-event-systems-205ae32f5e6b
Polyfill for old Safari and other incapable browsers:
https://github.com/ungap/event-target
2024 Update: Polyfill no longer needed in most cases.
Also, it's worth noting that Node.js supports EventTarget as of v15, so you can write the same code for both the server and the browser environments.
addEventListener
always expects EventListenerOrEventListenerObject
which does not respect custom events
Commented
May 22 at 0:58
While there is no native API akin to NodeJS' EventEmitter
, 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');
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
callbacks: { [s: string]: ((...args: any[]) => any)[] }
Commented
Jan 4, 2020 at 11:43
Create a customized event in the client, and attach to dom element:
var event = new Event('my-event');
// Listen for the event.
elem.addEventListener('my-event', 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
detail
property of the event object. So you can receive it from the other end by accessing that property in the event
object on the listener.
Commented
Aug 25, 2023 at 5:13
I ended up using this:
export let createEventEmitter = () => {
let callbackList: (() => any)[] = []
return {
on(callback: () => any) {
callbackList.push(callback)
},
emit() {
callbackList.forEach((callback) => {
callback()
})
},
}
}
2022 update: The BroadcatsChannel may provide a solution.
https://developer.mozilla.org/en-US/docs/Web/API/Broadcast_Channel_API
A very basic solution
function createEventEmitter() {
const events = {}
return {
on: (name, listener) => {
const listeners = events.hasOwnProperty(name)
? events[name]
: (events[name] = [])
listeners.push(listener)
},
emit: (name, ...params) => {
const listeners = events[name] || []
listeners.forEach((listener) => {
listener(...params)
})
},
}
}
const emitter = createEventEmitter()
emitter.on('myevent', (a, b) => {
console.log(a, b)
})
emitter.emit('myevent', 1, 2)
I have created an npm package that do the same. You can use in Javascript or Typescript event-emitter
Example
import { EventEmitter } from 'tahasoft-event-emitter';
const onStatusChange = new EventEmitter();
function updateStatus() {
// ...
onStatusChange.emit();
}
// somewhere else, we want to add a listener when status change
onStatusChange.add(() => {
// ...
});
I like the answer from Alparslan above. Here's one that uses the browser CustomEvent.
let EventEmitter = (function () {
let elem = document.createElement("div")
return {
on: function (name, cb) {
elem.addEventListener(name, (e) => cb(e.detail), false )
},
emit: function (name, data) {
elem.dispatchEvent(new CustomEvent(name, {detail: data}))
}
}
})()
[UPDATED to provide a fully working code]
Here is a complete code for implementing the EventEmitter class that can be used both in the browser and in node.
/*
This file is part of web3.js.
web3.js is free software: you can redistribute it and/or modify
it under the terms of the GNU Lesser General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
web3.js is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public License
along with web3.js. If not, see <http://www.gnu.org/licenses/>.
*/
/* eslint-disable max-classes-per-file */
import { EventEmitter as EventEmitterAtNode } from 'events';
// eslint-disable-next-line @typescript-eslint/no-explicit-any
type Callback = (params: any) => void | Promise<void>;
type EventTargetCallback = (params: CustomEvent) => void;
const wrapFunction =
(fn: Callback): EventTargetCallback =>
(params: CustomEvent) =>
fn(params.detail);
/**
* This class copy the behavior of Node.js EventEmitter class.
* It is used to provide the same interface for the browser environment.
*/
class EventEmitterAtBrowser extends EventTarget {
private _listeners: Record<string, [key: Callback, value: EventTargetCallback][]> = {};
private maxListeners = Number.MAX_SAFE_INTEGER;
public on(eventName: string, fn: Callback) {
this.addEventListener(eventName, fn);
return this;
}
public once(eventName: string, fn: Callback) {
const onceCallback = async (params: Callback) => {
this.off(eventName, onceCallback);
await fn(params);
};
return this.on(eventName, onceCallback);
}
public off(eventName: string, fn: Callback) {
this.removeEventListener(eventName, fn);
return this;
}
public emit(eventName: string, params: unknown) {
const event = new CustomEvent(eventName, { detail: params });
return super.dispatchEvent(event);
}
public listenerCount(eventName: string): number {
const eventListeners = this._listeners[eventName];
return eventListeners ? eventListeners.length : 0;
}
public listeners(eventName: string): Callback[] {
return this._listeners[eventName].map(value => value[0]) || [];
}
public eventNames(): string[] {
return Object.keys(this._listeners);
}
public removeAllListeners() {
Object.keys(this._listeners).forEach(event => {
this._listeners[event].forEach(
(listener: [key: Callback, value: EventTargetCallback]) => {
super.removeEventListener(event, listener[1] as EventListener);
},
);
});
this._listeners = {};
return this;
}
public setMaxListeners(maxListeners: number) {
this.maxListeners = maxListeners;
return this;
}
public getMaxListeners(): number {
return this.maxListeners;
}
public addEventListener(eventName: string, fn: Callback) {
const wrappedFn = wrapFunction(fn);
super.addEventListener(eventName, wrappedFn as EventListener);
if (!this._listeners[eventName]) {
this._listeners[eventName] = [];
}
this._listeners[eventName].push([fn, wrappedFn]);
}
public removeEventListener(eventName: string, fn: Callback) {
const eventListeners = this._listeners[eventName];
if (eventListeners) {
const index = eventListeners.findIndex(item => item[0] === fn);
if (index !== -1) {
super.removeEventListener(eventName, eventListeners[index][1] as EventListener);
eventListeners.splice(index, 1);
}
}
}
}
// eslint-disable-next-line import/no-mutable-exports
let EventEmitterType: typeof EventEmitterAtNode;
// Check if the code is running in a Node.js environment
if (typeof window === 'undefined') {
EventEmitterType = EventEmitterAtNode;
} else {
// Fallback for the browser environment
EventEmitterType = EventEmitterAtBrowser as unknown as typeof EventEmitterAtNode;
}
export class EventEmitter extends EventEmitterType {}
Ref: https://github.com/web3/web3.js/blob/4.x/packages/web3-utils/src/event_emitter.ts
You need a JavaScript library, like this https://github.com/Olical/EventEmitter?
Node gained a native EventTarget in Node 15 (Oct 2020;) this question no longer applies
https://nodejs.org/api/events.html#eventtarget-and-event-api