0

I tried to catch inline custom events from custom elements with the following code. I got only 'external success', never 'inline success' on logs.

Any ideas? Thank you.

Note : I have tried also to replace HTMLELement by HTMLDivElement/is: same result

customElements.define(
'test-it',class extends HTMLElement {
  connectedCallback() {
    this.children[0].addEventListener('click', e=>this.dispatchEvent(new CustomEvent('testevent', {detail:'test'})))
  };
}
);

document.getElementsByTagName('test-it')[0].addEventListener('testevent', ()=>{console.log('external success')});
<test-it id="test" ontestevent="console.log('inline success');">
  <div>Minimal test</div>
</test-it>
tit
  • 599
  • 3
  • 6
  • 25
  • 2
    I guess it's not about the custom element, [it's about the custom event](https://stackoverflow.com/a/42321978/11151040). – BOZ Jun 04 '21 at 09:03

2 Answers2

2

testevent is not a valid HTML5 Global Event Handler:

That means ontestevent="..." is just an attribute and not a onEvent handler.

You can not create such a handler yourself.

That is why addEventListener was created

PS. For your future Web Components adventures: Sending Events from inside shadowDOM (you are not using now) require composed:true for CustomEvents to escape shadowDOM

Danny '365CSI' Engelman
  • 16,526
  • 2
  • 32
  • 49
0

thanks BOZ, works with the following addition but custom event detail is lost (code updated).

if ( this.ontestevent ) this.ontestevent(); else eval(this.getAttribute('ontestevent'));

customElements.define(
'test-it',class extends HTMLElement {
  connectedCallback() {
    this.children[0].addEventListener(
      'click', 
      e=>{
        this.dispatchEvent(new CustomEvent('testevent', {detail:'test'}));
        if ( this.ontestevent ) this.ontestevent(); else eval(this.getAttribute('ontestevent'));
    })
  };
}
);

document.getElementsByTagName('test-it')[0].addEventListener('testevent', (e)=>{console.log('external success:'+e.detail)});
<test-it ontestevent="console.log('inline success:'+e.detail);">
  <div>Minimal test</div>
</test-it>
tit
  • 599
  • 3
  • 6
  • 25