簡體   English   中英

從自定義元素中移除事件監聽器

[英]Remove event listener from custom-elements

考慮一個簡單的自定義元素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>

無論我在哪里/如何選擇定義和執行事件偵聽器刪除,它都不起作用。

感謝您的任何回復,並提前致謝。

您正在創建依賴關系。

如果一個自定義元素添加了一個 EventListener,那么同一個自定義元素應該處理它的行為

 <my-element id=ELEMENT> <button id=BUTTON>Remove Listener</button> </my-element> <script> BUTTON.onclick = (evt) => ELEMENT.removeListener(); customElements.define('my-element', class extends HTMLElement { constructor() { super() // sets and return this-Scope.attachShadow({mode: 'open'}) // sets and returns this.shadowRoot.innerHTML = `<style>:host{display:inline-block}</style> <div>Simple element content<br> Click ME <slot></slot> </div>`; this.addEventListener('click', this.handleClick ) } handleClick(evt) { this.style.background = 'teal'; this.style.color = 'white'; } removeListener() { this.style.background = 'none'; this.style.color = 'red'; this.removeEventListener('click', this.handleClick); this.shadowRoot.querySelector("div").innerText = `Event Listener "handleClick" removed`; } }); </script>

內聯事件

而不是addEventListener (可以添加多個事件)
您還可以使用內聯事件(可能只有一個 function)

不僅符號更短,它還使您的組件用戶更容易覆蓋行為。

// assign
this.onclick = this.handleClick;
// remove
this.onclick = null;

另請注意,當從 DOM 中刪除元素時, JavaScript 垃圾收集過程將刪除您分配給元素的事件。 因此,您不必自己刪除這些偵聽器。

如果您的元素將偵聽器添加到其他元素(例如document ),則您必須刪除它們,
disconnectedCallback

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM