You cannot use a string name as a function reference in the callback. However, using an anonymous function with eval()
may work, although not recommended.
That is because technically speaking you can use eval()
to invoke a function by its name and then use <functionName>.apply(null, arguments)
to call it with the same arguments the callback receives.
However, I would not recommend this solution because eval()
in general is frowned upon as it presents security risks. Is there a reason why you want to use a dynamic function name?
function myFunctionName_OnClick(e) {
console.log('clicked');
// Verify that event is passed correctly
console.log(e.target);
}
var elementValue = document.createElement("button");
elementValue.innerText = 'Click me!';
var stringName = "myFunctionName_OnClick";
elementValue.addEventListener('click', function() {
eval(stringName + '.apply(null, arguments)');
});
document.body.appendChild(elementValue);