skip to Main Content

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


  1. 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

    Login or Signup to reply.
  2. 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.

    const div = document.querySelector("div");
    const attributeValue = div.getAttribute("data-callback");
    
    
    const myModule = {
      // this is just an example, if you import the whole module, all exported functions will be accessible on the module by name
      fooBar: () => console.log("I got called!")
    };
    
    myModule[attributeValue]?.();
    <div data-callback="fooBar"/>
    Login or Signup to reply.
  3. 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);
        }
      }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search