Custom Web Component Event Call Back Function In Tag
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
Solution 1:
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>`classUioKeyextendsHTMLElement {
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.
Solution 2:
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.
classUioKeyextendsHTMLElement {
constructor() {
super()
this.attachShadow( { mode: 'open' } )
.innerHTML = uio-key-temp.innerHTML
}
eKey(){
window.alert('class eKey function' )
}
}
customElements.define( 'uio-key', UioKey )
<templateid="uioKeyTemp"><style>.i { background: gray ; height: 10pt } </style><divclass="uio-key"><divclass="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).
Post a Comment for "Custom Web Component Event Call Back Function In Tag"