Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
// Publish-Subscribe
// Observable – Observer
// Publisher - Listener
// Emitter - Handler
/*
Updates:
0) off
1) once
2) raise event on add listener
3) raise event on remove listener
4) ...
*/
function Emitter() {
let handlers = {}
return {
on: (eventName, handler) => {
if (handlers[eventName]) {
handlers[eventName].push(handler)
} else {
handlers[eventName] = [handler]
}
},
emit: (eventName, ...args) => {
for (handler of handlers[eventName]) {
handler(...args)
}
}
}
}
let emitter = Emitter()
emitter.on("bar", function handler3(...args) {
console.log(`handler3 sees <bar> with args=${args.join(", ")}`)
})
emitter.on("foo", function handler1(...args) {
console.log(`handler1 sees <foo> with args=${args.join(", ")}`)
})
emitter.on("foo", function handler2(...args) {
console.log(`handler2 sees <foo> with args=${args.join(", ")}`)
})
emitter.on("bar", function handler4(...args) {
console.log(`handler4 sees <bar> with args=${args.join(", ")}`)
})
emitter.emit("foo", 1, "a")
emitter.emit("bar", 2)
emitter.emit("foo", 2, 0)
emitter.emit("foo", 3)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment