I’m working with custom elements which execute a callback after something happens.
When adding this element in HTML,
<custom-element callback="change(this)"></custom-element>
how can we convert the callback attribute value to the function and execute it, like the common onclick attribute (without eval)?
<div onclick="change(this)"></div>
class CustomElement extends HTMLElement {
constructor() {
super();
}
connectedCallback() {
let func = this.getAttribute('callback'); //and then?
}
}
3
Answers
To convert an HTML element attribute value string to a function, particularly for attributes like onclick, you need to dynamically create a function from the string and then assign it to the element’s event handler.
The preferred method is to use the Function constructor or addEventListener with dynamically created functions. This way, you avoid using eval and keep your code more maintainable and secure
If you don’t want to use eval it means you have a finite number of functions that can be called. If so why not create some sort of dictionary with all possible callbacks and use the attribute to just store a name for the particular function.
This way you can have a module with all functions and just access the exported function by name.
You can get the
attribute
value ( the function name ), then create a function reference fromFunction
constructor with the first argument as the parameter name ( the custom element ) and the second argument being the function content which is the attribute value ( the function to execute ), then execute the function reference with passingthis
as an argument ( the custom element )