标签中的自定义Web组件事件回调函数 [英] 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>
当在.i div上单击时,忘记了正在触发的文档ekey,我想要 要触发的类ekey() 如果我省略文件eKey()功能,我会得到函数eKey()未定义
onclick
仅适用于全局定义的函数.
这是一个非常快速的技巧,可让您使用类函数.
// 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/>
我使用自定义属性on-click
作为获取所有需要单击处理程序的元素的方法,然后我将该属性的值用作并将其用作类函数名称,并将其传递给addEventListener
函数./p>
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
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.
这篇关于标签中的自定义Web组件事件回调函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!