Skip to content

Instantly share code, notes, and snippets.

@nlf
Last active May 7, 2019 15:39
Show Gist options
  • Save nlf/4684b9e89697eb56482aef2752168b00 to your computer and use it in GitHub Desktop.
Save nlf/4684b9e89697eb56482aef2752168b00 to your computer and use it in GitHub Desktop.
class EventEmitter {
constructor() {
this.listeners = {}
}
addListener(event, fn) {
if (!this.listeners[event]) {
this.listeners[event] = []
}
this.listeners[event].push(fn)
}
removeListener(event, fn) {
if (!this.listeners[event]) {
this.listeners[event] = []
}
for (let i = 0; i < this.listeners[event].length; ++i) {
if (this.listeners[event][i] === fn) {
this.listeners[event].splice(i, 1)
break
}
}
}
emit(event, payload) {
if (!this.listeners[event]) {
this.listeners[event] = []
}
for (const handler of this.listeners[event]) {
handler(payload)
}
}
}
// usage
const events = new EventEmtiter()
events.addListener('fart', function (person) { console.log(person, 'farted') })
events.emit('fart', 'paul')
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment