Skip to content

Instantly share code, notes, and snippets.

@ivan-kleshnin
Created November 20, 2016 21:04
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 2 You must be signed in to fork a gist
  • Save ivan-kleshnin/a7ec0d090487d6d9120b2c61ae7293a7 to your computer and use it in GitHub Desktop.
Save ivan-kleshnin/a7ec0d090487d6d9120b2c61ae7293a7 to your computer and use it in GitHub Desktop.
// 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