Skip to main content

Event Emitter

GitHub code size in bytes GitHub

Strictly typed Event Emitter for Deno (and browser after compilation to js).
It’s essentially an optimized version of EventEmitter3 used by Node however this version is over 18 times smaller and contains only those methods people actually use.

Usage

import { EventEmitter } from "https://deno.land/x/event_emitter/mod.ts"

// Define what events you want to use. EventEmitter will provide IntelliSense support based on your event types.
interface ConnectionEvents {
    connected: () => void
    disconnected: (reason: string) => void
    error: (errorCode: number, reason?: string) => typeof Error
    handshake: (interval: number) => Promise<boolean> // Asynchronous callback
}

class Connection extends EventEmitter<ConnectionEvents> {
    // Your own class
}

const conn = new Connection()

// EventEmitter#once attaches new listener and deletes it after first execution.
conn.once('connected', () => console.info('Successfully connected!'))

// EventEmitter#on attaches listener that will work continuously until you delete it manually using EventEmitter#off method.
conn.on('error', (code, msg) => console.error(`Caught error: [${code}] ${msg}`))



// Trigger your listener(s) by emitting signal somewhere in your code:
conn.emit('error', 429, 'rate limit')

Raw usage

You can use it just like that, without need of extending class or providing interface.

import { EventEmitter } from "https://deno.land/x/event_emitter/mod.ts"

// let's this time increase maxListeners limit to 20 cause why not.
// Normally it's blocked on 5 to prevent memory leaks in poorly made codes.
const emitter = new EventEmitter(20)

// You cannot be fully sure of received args in this case (no interface).
emitter.on('hello', (name?: string) => {
    if (name && typeof name === 'string') console.log(`Hello ${name}!`)
    else console.warn(`Received invalid arg. Expected "string" but received "${typeof name}".`)
})

emitter.emit('hello', 'David') // Output: Hello David!

emitter.emit('hello', 24) // Output: Received invalid arg. (...)

emitter.off('hello') // Deletes entire event & all its listeners.
// EventEmitter#off returns boolean signal to inform about result.

emitter.emit('hello', 'David') // No reaction

Remember to use EventEmitter#once over EventEmitter#on if you want to catch this state only once (ex. ready event). Try to avoid attaching more than 5 listeners to single event, this maxListeners limit is here for a reason! Potentially you can attach thousands of listeners if you don’t care about performance.

Author

Event Emitter © Amatsagu.
Authored and maintained by Amatsagu.