Created
January 31, 2020 14:45
-
-
Save jgaskins/df9cc65834f5467dc36490f3c2dbcc73 to your computer and use it in GitHub Desktop.
Managing your own DOM event handlers in JS
This file contains hidden or 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
/* Data structure to hold our event handlers. It's important that when you | |
remove an element from the DOM that you delete its associated event | |
handler id to avoid memory leaks. | |
{ | |
12345: { // DOM element's event handler id | |
click: [ | |
function(event) { ... }, | |
] | |
}, | |
} | |
*/ | |
const events = {} | |
function eventHandler(event) { | |
event.target.eventHandlerID || event.target.eventHandlerID = Math.random() | |
const handlerID = event.target.eventHandlerID | |
events[handlerID] || events[handlerID] = {} | |
events[handlerID][event.type] || events[handlerID][event.type] = [] | |
events[handlerID][event.type].forEach(handler => handler(event)) | |
} | |
document.addEventListener('click', eventHandler) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment