I have a project which has a large number of controls (buttons, checkboxes, etc.) that I’m trying to find a way to add events to without directly putting the code in the html or in the main javascript/jquery file. Rather, I’d like to store the event code in a config file so that I can make changes if needed without having to touch the main code and so I don’t have a massive amount of repeating code just to assign actions.
The HTML has controls like this:
<id="elem1">
<id="elem2">
<id="elem3">
...
And then there is a separate JS config file which has an object like this:
btnAssign: [
{ el: '#elem1', onEvent: 'click', action: "someAction();" },
{ el: '#elem2', onEvent: 'change', action: "someOtherCode();someOtherCode2();" },
{ el: '#elem3', onEvent: 'click', action: "doSomethingElse();" }
...
]
What I want to do is now assign the “action” for the specified “onEvent” to the listed “el”. As an example, I want to add someAction();
to elem1
‘s onclick
event so that when I click on elem1
, someAction();
gets executed.
In the main JS/Jquery file, the following works perfectly, but only if I use eval()
btnAssign.forEach((assignment) => {
$(assignment.el).on(assignment.onEvent, function () {
eval(assignment.action);
});
});
Based on reading (https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/eval) I’d really like to find another way to accomplish this without the potential risks. I tried using indirect eval?.
but some of the entries (not all) fail.
Is there a safer or better way to do this?