Created
June 28, 2016 12:38
-
-
Save lionelB/7f18aa8fbd5994489ccde04ecd716368 to your computer and use it in GitHub Desktop.
a small event dispatcher based on es6 Map/Set
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 dispatcher = () => { | |
const eventMap = new Map() | |
const getHandlers = (name) => { | |
if ( !handlers.has(name)) { | |
handlers.set(name, new Set()) | |
} | |
return eventMap.get(name) | |
} | |
const on = ({name, fn}) => { | |
const handlers = getHandlers(name) | |
handlers.add(handler) | |
return () => { | |
handlers.delete(handler) | |
} | |
} | |
const dispatch = ({name, payload}) => { | |
getHandlers(name).forEach((handler) => handler(payload)) | |
} | |
return { dispatch, on } | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment