custom web component event call back function in tag

class UioKey extends HTMLElement {
 ...
 eKey(){windows.alert('class  eKey function')}
 
 
 }
 
 function eKey(){
 eKey(){windows.alert('document eKey function')}
<template id="uio-key-temp">
    <div class="uio-key">
         <div class="i" onclick="eKey()"></div><span></span>
    </div>
</template>    

when clikcing on the .i div agot the document ekey that is firing, i want the class ekey() to be fired if i omit the dodument eKey() fuction i got function eKey() undefined

Answers:

Answer

onclick will only work with globally defined functions.

Here is a very quick hack that allows you to use a class function.

// Class for `<uio-key>`
class UioKey extends HTMLElement {
  constructor() {
    super();

    let shadow = this.attachShadow({mode: 'open'});
    shadow.innerHTML = '<div><div on-click="eKey">div</div><span>span</span></div>';
    let a = shadow.querySelectorAll('[on-click]');
    a.forEach(
      el => {
        const handlerName = el.getAttribute('on-click');
        el.addEventListener('click', this[handlerName]);
      }
    );
  }

  eKey() {
    window.alert('class  eKey function');
  }
}

// Define our web component
customElements.define('uio-key', UioKey);
<hr/>
<uio-key></uio-key>
<hr/>

I use a custom attribute on-click as a way to grab all elements that want a click handler then I take the value of that attribute and use it as the class function name and pass it into the addEventListener function.

Answer

Alternatly to @Intervalia's answer, you could use the getRootNode() method and then the host property to access the Custom Element object from inside the Shadow DOM.

class UioKey extends HTMLElement {
  constructor() {
    super()
    this.attachShadow( { mode: 'open' } )
        .innerHTML = uio-key-temp.innerHTML
  }
  eKey(){ 
    window.alert('class eKey function' ) 
  }
}
customElements.define( 'uio-key', UioKey )
<template id="uioKeyTemp">
    <style> .i { background: gray ; height: 10pt } </style>
    <div class="uio-key">
         <div class="i" onclick="this.getRootNode().host.eKey()"></div>
    </div>
</template>
<uio-key></uio-key>

Note that it's always a good practice to use inline scripts because in some situations they can be disabled (for security reasons).

Tags

Recent Questions

Top Questions

Home Tags Terms of Service Privacy Policy DMCA Contact Us

©2020 All rights reserved.