Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

can i pass function as attribute to web component?

I'm trying to create a native web component for input element. I wanted the component to have custom validation functionality, similar to polymer's paper-input custom validator function. I'm not sure if I can pass a custom validator function as attribute to an instance of (web component) input element. Any suggestions would be appreciated.

like image 232
PS. Avatar asked Jun 14 '18 20:06

PS.


1 Answers

Just pass it to the constructor. Your custom element statement:

class CustomInput extends HTMLElement {
  constructor(validator) {
    super()
    this.validate = validator
  }

  /* Your Custom Input Methods */
}

And then instantiate your component via the new operator instead of the document.createElement.

Instantiation:

const customInputEl = new CustomInput((inputString) => {
  // your validation code
})

If you want to pass a function to the component, it must mean that you instantiate it via javascript anyway.

like image 83
gottfried Avatar answered Oct 03 '22 20:10

gottfried