Search code examples
javascriptweb-componentcustom-elementnative-web-component

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.


Solution

  • An attribute is a string, not a function. You can pass a a function as a string and then evaluate it with the eval() function. It's not considered as a good practice, for security reasons.

    Another solution is to pass it to the custom element as a Javascript property:

    function validate( value ) { return Number.isInteger( value) }
    myCustomElement.validation = validate
    

    Or, using a arrow function:

    myCustomElement.validation = v => Number.isInteger( va )
    

    class CustomInput extends HTMLElement {
        constructor() {
            super()
            var sh = this.attachShadow( { mode: 'open' } )
            sh.appendChild( tpl.content.cloneNode( true ) )
            
            var div = sh.querySelector( 'div' )
            div.addEventListener( 'input', () => { 
               if ( !this.validate( Number( div.textContent ) ) )
                div.classList.add( 'error' )
               else
                div.classList.remove( 'error' ) 
            } )        
        }
    }
    
    customElements.define( 'custom-input', CustomInput )
    
    integer.validate = v => Number.isInteger( v )
    <template id="tpl">
      <style>
        :host {
           display: inline-block ;
           min-width: 150px ;
           border: 1px solid cyan ;
        }
        
        div.error {
           color: red ;
        }
    
      </style>
      <div contenteditable></div>
    </template>
        
    <custom-input id="integer"></custom-input>