can i pass function as attribute to web component?

前端 未结 3 996
慢半拍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:17

    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 )
    
        
    

提交回复
热议问题