-
-
Notifications
You must be signed in to change notification settings - Fork 1k
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Didn't save the extracted ListenerController.
- Loading branch information
1 parent
3344476
commit f448775
Showing
2 changed files
with
147 additions
and
64 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,41 @@ | ||
// This is a more modern way to handle disconnecting listeners on demand. | ||
|
||
// example usage: | ||
|
||
/* | ||
export class MyElement extends LitElement { | ||
this.listenerController = new ListenerController(); | ||
connectedCallback() { | ||
super.connectedCallback(); | ||
window.addEventListener("event-1", handler1, { signal: this.listenerController.signal }); | ||
window.addEventListener("event-2", handler2, { signal: this.listenerController.signal }); | ||
window.addEventListener("event-3", handler3, { signal: this.listenerController.signal }); | ||
} | ||
disconnectedCallback() { | ||
// This will disconnect *all* the event listeners at once, and resets the listenerController, | ||
// releasing the memory used for the signal as well. No more trying to map all the | ||
// `addEventListener` to `removeEventListener` tediousness! | ||
this.listenerController.abort(); | ||
super.disconnectedCallback(); | ||
} | ||
} | ||
*/ | ||
|
||
export class ListenerController { | ||
listenerController?: AbortController; | ||
|
||
get signal() { | ||
if (!this.listenerController) { | ||
this.listenerController = new AbortController(); | ||
} | ||
return this.listenerController.signal; | ||
} | ||
|
||
abort() { | ||
this.listenerController?.abort(); | ||
this.listenerController = undefined; | ||
} | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters