且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

Vanilla Web Component自定义事件属性和属性

更新时间:2023-02-15 18:38:35

事件监听器解决方案(第三个)是最简单的,因为您不必定义任何特殊的事件来捕获事件。

The event listener solution (the third one) is the easiest because you don't have to define anything special to catch the event.

事件处理程序解决方案需要创建一个 eval()(第一个,来自属性)或明确调用该函数(第二个)一个)。

The event handler solutions need to make an eval() (first one, from attribute) or to call the fonction explicitely (second one).

如果你不能使用 eval ,你可以改为解析属性字符串。

If you can't use eval you can instead parse the attribute string.

customElements.define( 'x-pop-out', class extends HTMLElement {
    connectedCallback() {
        this.innerHTML = `<button id="Btn">pop</button>`

        this.querySelector( 'button' ).onclick = () => {
            this.dispatchEvent( new CustomEvent( 'pop' ) )
            if ( this.onpop )
                this.onpop()
            else
                eval( this.getAttribute( 'onpop' ) )
        }            
    }
} )

XPO.addEventListener( 'pop', () => console.info( 'pop' ) )

<x-pop-out id=XPO onpop="console.log( 'onpop attribute' )"></x-pop-out>
<hr>
<button onclick="XPO.onpop = () => console.log( 'onpop override' )">redefine onpop</button>