ARTICLE AD BOX
My application creates a page dynamically and contains lots of buttons that when clicked, modify the page and create more links.
Initially, I wrote a function to create a button, add a click event handler with an inline function that typically does something complex - calling a few functions with complex parameters.
const addType1Button = (label, func, args) => { const id = crypto.randomUUID(); const html = `<span id=${id}`>${label} - Click Me</span> leftSideDiv.addEventListener('click', ev => { func(..args); }) }Then, in my code at various points, I call something like `addType1Button("label", doSomething, ["A", "B"])` many times and it works okay but of course, I end up with many many event listeners (hundreds or thousands eventually) and no obvious way to delete them. I tried using the AbortController method I read about but couldn't get it to work.
My new approach is to create the fragments of HTML the same way with a unique ID, push an object with the id and a function into an array each time I create a button.
const addType1Button = (label, func, args) => { const id = crypto.randomUUID(); const html = `<span id=${id}`>${label} - Click Me</span> handlers.push({ id: id, fn: () => { func(...args) }; } }Then, I have a single click event listener on document, and the handler for that looks through the handlers array for a matching ID in the incoming event and if found, calls the function.
As is, the handlers array just grows forever but I intend to have some code that removes unused entries periodically.
It works well but is this a reasonable approach?
How does the function that is pushed into the array retain the function and argument values that are passed in to the function where it's called?
The app has different sections (divs really) so my plan to stop the array growing too big was to add a section name to each handler entry and so when that section is recreated after a button press somewhere else, I scan through the handler array and delete any entries that match the section I am recreating.
My question: is it terribly inefficient to scan an array of several hundred objects, looking for a string in one of the objects and then deleting it from the array?
Thanks in advance - this approach will be the foundation of something more complex and I am keen to get it right and make sure I understand everything before I proceed.
