javascripthtmlelement

How to convert HTML element attribute value string to function like onclick


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?
  }
}

Solution

  • You can get the attribute value ( the function name ), then create a function reference from Function 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 passing this as an argument ( the custom element )

      connectedCallback() {
        let attrValue = this.getAttribute('callback');
        if (attrValue) {
        let callbackFunction = new Function('element', `${attrValue};`).bind(this);
    
          callbackFunction(this);
        }
      }