A chat client has one socket and many parts of the page that care about it: the message list, the unread badge, the typing indicator. None of them should know about the others. An event emitter sits in the middle: parts subscribe to a named event, and whoever owns the socket announces the event once. Every listener hears it, in order.
emit(name, ...args) calls every listener of name with all of args, in the order the listeners were added, with this set to the emitter.
emit returns true when name had at least one listener, and false otherwise.
Events are separate by name, and no name is special: "constructor" has no listeners until someone adds one.
on, once and off return the emitter, so calls can be chained.
Each on is its own registration: the same function added twice runs twice.
off(name, listener) removes one registration of listener, the most recently added one. An unknown event or listener changes nothing.
once(name, listener) registers a listener for the next emit only. off(name, listener) with the same function removes it before it runs.
A once listener is removed before it is called, and it never runs twice, even when the listener (or another listener) emits the same event again.
emit calls the listeners that were registered when it started. A listener added during an emit first runs in the next one; a listener removed during an emit still runs in that one, and not after.
listenerCount(name) returns the number of registrations of name, on and once alike.
on and once throw a TypeError when listener is not a function, and register nothing.
conste=newEventEmitter();consta= () => console.log("a");e.on("x", a).on("x", () => console.log("b")).on("x", a);e.off("x", a); // removes the second a, the most recent onee.emit("x"); // "a", then "b"
JAVASCRIPT
conste=newEventEmitter();e.on("x", () => { console.log("first"); e.on("x", () => console.log("late"));});e.emit("x"); // "first" only: "late" was added during this emite.emit("x"); // "first", "late"