Skip to content

Instantly share code, notes, and snippets.

@mfbx9da4

mfbx9da4/eventEmitter.ts

Last active Apr 9, 2021
Embed
What would you like to do?
An event emitter in 10 lines
type Listener<T> = (val: T) => void
export const createEmitter = <T>() => {
const listeners: Set<Listener<T>> = new Set()
const subscribe = (x: Listener<T>) => {
listeners.add(x)
return () => listeners.delete(x)
}
const emit = (val: T) => {
for (let x of listeners.values()) x(val)
}
return { subscribe, emit }
}
const emitter = createEmitter<string>()
const listener1 = emitter.subscribe((x) => console.log(1, x))
const listener2 = emitter.subscribe((x) => console.log(2, x))
emitter.emit('foo')
// destroy the listeners
listener1()
listener2()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment