Last active
May 7, 2019 15:39
-
-
Save nlf/4684b9e89697eb56482aef2752168b00 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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