I need to dynamically pass in a function name that will be added as an onclick event handler as part of a dynamic UI creator. Most of the function is easy but I can't work out how to turn the string function name into the function that is bound to the event handler.
I've tried things like:
// Add event handlers
Object.keys(compToAdd.events).forEach( (type) => {
newEl.addEventListener( type, Function.prototype.bind( compToAdd.events[type] ) )
})
But that doesn't work.
Also tried:
window.mycb = function() {
console.log('>>>> hello >>>>')
}
// ...
Object.keys(compToAdd.events).forEach( (type) => {
newEl.addEventListener( type, window['mycb'] )
})
Using window['mycb']()
immediately executes the fn when applied to the event listener which is obviously not correct. Without ()
, nothing happens when the click event fires.