我可以将功能作为属性传递给Web组件吗? [英] can i pass function as attribute to web component?

查看:82
本文介绍了我可以将功能作为属性传递给Web组件吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试为输入元素创建本机Web组件.我希望组件具有自定义验证功能,类似于Polymer的纸张输入自定义验证器功能.我不确定是否可以将自定义验证器函数作为属性传递给(Web组件)输入元素的实例.任何建议,将不胜感激.

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.

推荐答案

属性是字符串,而不是函数.您可以将函数作为字符串传递,然后使用eval()函数对其进行评估.出于安全原因,这不被认为是一种好习惯.

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.

另一种解决方案是将其作为Javascript属性传递给自定义元素:

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

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

或者,使用箭头功能:

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>

这篇关于我可以将功能作为属性传递给Web组件吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆