Home > database >  Vanilla JS Reusable Dynamic Function taken as a string
Vanilla JS Reusable Dynamic Function taken as a string

Time:12-01

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!

CodePudding user response:

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");
  • Related