can i pass function as attribute to web component?

前端 未结 3 997
慢半拍i
慢半拍i 2021-02-20 04:35

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 validato

3条回答
  •  北恋
    北恋 (楼主)
    2021-02-20 05:19

    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.

提交回复
热议问题