Created
June 29, 2020 20:16
-
-
Save gahabeen/c3d2446d9aa1704f267d5a09e989bfa3 to your computer and use it in GitHub Desktop.
EventBus - Vanilla JS
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 EventBus { | |
registry = new Map() | |
constructor() {} | |
on(type, handler) { | |
const handlers = this.registry.get(type) | |
const added = handlers && handlers.push(handler) | |
if (!added) { | |
this.registry.set(type, [handler]) | |
} | |
} | |
off(type, handler) { | |
const handlers = this.registry.get(type) | |
const handlerIndex = handlers.indexOf(handler) | |
if (handlers && handlerIndex > -1) { | |
handlers.splice(handlerIndex, 1) | |
} | |
} | |
emit(type, payload) { | |
this.registry | |
.get(type) | |
.slice() | |
.map((handler) => handler(payload)) | |
} | |
} |
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
const bus = new EventBus() | |
function test(p) { | |
console.log('test!', payload) | |
} | |
bus.on('test', test) | |
bus.on('test1', (payload) => console.log('test 1!', payload)) | |
bus.off('test', test) | |
bus.emit('test1') | |
bus.emit('test') |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment