95

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

12 Answers 12

155

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:

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.

2
  • It is not TS friendly with custom events. The addEventListener always expects EventListenerOrEventListenerObject which does not respect custom events
    – Alexey Sh.
    Commented May 22 at 0:58
  • @AlexeySh. Fix your type defs then?
    – Brad
    Commented May 22 at 4:52
22

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');
5
  • 8
    OP is looking for a working on a native implementation on a browser not requiring a npm package.
    – Ivan
    Commented Oct 9, 2020 at 7:42
  • 17
    @Ivan SO answers aren't just for the OP. 😉 This is the answer I was looking for, and looking at the votes, other people too. I want the same code to work in both environments.
    – Inigo
    Commented Apr 10, 2022 at 3:34
  • 1
    @Inigo In that case, you should have looked up or asked a different question which targets your requirement specifically. This answer, although correct, is just noise because it doesn't address what the OP is asking for. Commented Aug 19, 2023 at 4:39
  • 3
    @vighnesh153 I would argue that inundating SO with questions that differ in very tiny ways adds noise. Better to collect a variety of solutions to the crux of a problem under one question. Not to mention that the wording of the question, what people see in search results, "Is there any EventEmitter" instead of "Is there something like node's EventEmitter in browsers", if anything makes this the more valid answer. Not sure why you're nit-picking.
    – Inigo
    Commented Aug 19, 2023 at 11:36
  • I'll remove this answer if it's redundant or unnecessary. So, I'll assess it by checking if this comment receives 3 upvotes.
    – Amir Gorji
    Commented Sep 19, 2023 at 10:25
14

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

2
  • 1
    Typescript: callbacks: { [s: string]: ((...args: any[]) => any)[] } Commented Jan 4, 2020 at 11:43
  • 5
    This will result in out-of-order event handling when a event handler emits another event. You probably want to call the callbacks in emit after it returns, with setTimeout. Or put the events in a queue. Commented Jul 28, 2021 at 16:39
6

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

2
  • 11
    This only works on HTML elements, the question is how to make it work on an object like you can do in Node.
    – Kokodoko
    Commented Sep 23, 2019 at 12:00
  • If you want to attach data within the dispatching event, you have to provide that in the 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
3

I ended up using this:

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

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

1
  • Make sure to also add a cleanup functionality to avoid memory leaks. Commented Aug 19, 2023 at 4:39
2

2022 update: The BroadcatsChannel may provide a solution.

https://developer.mozilla.org/en-US/docs/Web/API/Broadcast_Channel_API

3
  • Only for web workers...
    – smac89
    Commented Sep 2, 2022 at 3:48
  • 1
    it works just fine in browser too. in MDN it says : "The Broadcast Channel API allows basic communication between browsing contexts (that is, windows, tabs, frames, or iframes) and workers on the same origin."
    – Nir
    Commented Sep 3, 2022 at 5:06
  • While this is a great solution (especially for communicating between tabs and web/service workers), it also has more overhead than a simple event target, because it has the additional task of communicating between processes. If your goal is to create an event listener within a single page, Brad's answer is probably the best option.
    – THEtheChad
    Commented Nov 9, 2022 at 6:23
2

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)
1

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(() => {
  // ...
});

0

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}))
        } 
    }

})()
-1

[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

-3

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

1
  • 4
    Not exactly, i want some the native one, instead of third part lib. Thanks.
    – Xin
    Commented Aug 23, 2017 at 7:07
-3

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

1
  • 1
    this question is about browser, not server side Commented Nov 22, 2022 at 7:53

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.