Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Vanilla JS Reusable Dynamic Function taken as a string

I’m trying to make a reusable function that can take in a dynamic "action" for reusability…

In this case, adding the background color is the action.

const button = document.querySelector("#button");
const items = document.querySelectorAll(`*[id^="eventHandlerCreatedItem"]`); 

var eventHandler = (refEl, event, focusEls, action) => {
    refEl.addEventListener(`${event}`, () => {
        focusEls.forEach((focusEl) => {
            // focusEl.style.backgroundColor = "orange"; // works
            focusEl.`${action}`; // doesn't work
        });
    });
};

eventHandler(button, "click", items, 'style.backgroundColor = "orange"');

Thanks!

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

Don’t use a string for this. An "action" semantically describes a "function", use a function:

var eventHandler = (refEl, event, focusEls, action) => {
    refEl.addEventListener(`${event}`, () => {
        focusEls.forEach((focusEl) => {
            action(focusEl);
        });
    });
};

eventHandler(button, "click", items, (el) => el.style.backgroundColor = "orange");
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading