【发布时间】:2021-05-24 14:14:56
【问题描述】:
考虑一个简单的自定义元素simple-element 我无法移除事件监听器:
const myElement = document.getElementById('myElement');
function removeListener(){
// works
this.style.backgroundColor = '';
this.style.color = 'red';
// NOT WORKING
this.removeEventListener('click', handleEvent.bind(this));
this.span.innerText = 'Event Listener "handleEvent" not removed, you can still click this "simple-element"'
}
function handleEvent(){
this.style.backgroundColor = '#069';
this.style.color = '#ffffff'
}
// sample custom element
(() => {
class SimpleElement extends HTMLElement {
constructor() {
super();
this.template = document.createElement('template');
this.template.innerHTML =
`<style>span {color: inherit}</style>
<span>Simple element content<br>Click ME</span>`;
// Patch shadow DOM
if (window.ShadyCSS) {
window.ShadyCSS.prepareTemplate(this.template, 'simple-element');
}
this.attachShadow({ mode: 'open' });
this.shadowRoot.appendChild(this.template.content.cloneNode(true));
// Patch shadow DOM
if (window.ShadyCSS) {
window.ShadyCSS.styleElement(this)
}
}
connectedCallback(){
this.span = this.shadowRoot.querySelector('span');
this.addEventListener('click', handleEvent.bind(this))
}
}
customElements.define('simple-element', SimpleElement);
})();
simple-element {padding: 1rem 0.25rem; width: 100%; display: block}
<simple-element id="myElement"></simple-element>
<br>
<button onclick="removeListener.call(myElement)">Remove Listener</button>
无论我选择在哪里/如何定义和执行事件侦听器移除,它都不起作用。
感谢任何回复,并提前致谢。
【问题讨论】:
-
.bind()每次调用时都会返回一个新函数,这就是我认为事件监听器没有被删除的原因。 -
.apply有同样的效果吗? -
不,
call和apply不返回新函数,bind返回新函数。 -
你有什么建议?
this.addEventListener('click', handleEvent.apply(this))不起作用。 -
handleEvent.apply(this)- 这不起作用,因为它会立即调用函数
标签: javascript html custom-element