Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

<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);
    }
  }
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading