Using Web Components without any framework, what is the proper way to implement a custom event? For example, say I have a custom element x-pop-out
that has a custom event of pop
I would want all of the following to work:
<x-pop-out onpop="someGlobal.doSomething()"/>
var el = document.getElementsByTagName('x-pop-out')[0];
el.onpop = ()=> someGlobal.doSomething();
//or
el.addEventListener('pop', ()=> someGlobal.doSomething());
The last one I get how to do, but do I need to custom implement the attribute and a getter / setter for each? Also, is eval()
the appropriate way to execute the string from the attribute?
The event listener solution (the third one) is the easiest because you don't have to define anything special to catch the event.
The event handler solutions need to make an eval()
(first one, from attribute) or to call the fonction explicitely (second one).
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>